How To Convert PSD To HTML And CSS For Your Websites

Most designers have the ability to create a professional websites in software’s like Photoshop, but are not able to convert a PSD files to a W3C valid HTML and CSS code that could be optimized for search engines. In order to learn these you can follow PSD to HTML tutorials that are found easily on the internet. By following these you can bring the theory directly into practice. But it seems to be difficult to understand for the beginners. This roadmap will help the beginners to complete the PSD to HTML tutorials successfully.
  • Visit the W3Schools website. All elements of HTML and CSS are explained there very precisely. You can also view that how these things are put into practice. If you read the theories from the book than you can buy a book explaining the principles of HTML and CSS. Be sure that you buy the book that contains exercises, so you can try it yourself through which you can learn more, rather than from the theories alone.
  • Go through the category pages i.e. ‘HTML tutorial’ and ‘CSS tutorial’. You can find the basic tutorials on HTML and CSS. The theories that you have read on the W3Schools website, you can put into practice here. Most of these contain video tutorials, which gives you the opportunity to practice a lot. Reading alone is not enough if you want to learn HTML and CSS! You have to be able to put it in into practice. You should make familiar yourself with all the HTML and CSS elements and properties so that you are always aware of the opportunities that you have. You must practice as many HTML and CSS tutorials as possible until you become a master of your own.
  • When you believe to have mastered HTML and CSS well, it is the time for you for more advanced tutorials. For this you can go through the website at Net.tutsplus.com. A lot of advanced tutorials can be found here very easily, which will help you to get the perfect knowledge on this regard.
  • If you have become a master with HTML and CSS than you can go on finding for the tutorials related with slicing psd files. Be aware that many of these tutorials are out of date. In these tutorials only the slice tool is used, which creates unnecessary images. If you use more images your site will load slowly. You must make sure that you slice the text on your website as little as possible. This will make it possible to minimize the images and to place them next to each other for a number of times.

Hope these above points will help you to convert PSD to HTML and CSS in a more effective manner in no time.

Ask Siri to Buy Movie Tickets in iOS 6.1

Ask Siri to Buy Movie Tickets in iOS 6.1

Apple has released Software update -iOS 6.1-which gives you the ability to purchase movie tickets through Fandango using Siri.As for Siri, Apple relentlessly continues to make progress in this technology from the future.In the recent iOS 6.1 release, Apple has empowered Siri with the ability to interface with Fandango.The result is that we are now able to have our faithful assistant find movies, help us purchase our tickets, and take advantage of the convenience Passbook gives us.

In iOS 6.1, Passbook now includes a friendlier, easy-to-understand help page with a button that links to an App Store list of downloadable apps that support Passbook. Incidentally, the Fandango app was one of the very first to support Passbook.When you purchase a movie ticket, either via the app or by way of the Fandango.com website, you are clearly presented with several options for electronic admission to the movie. One option is to have a Passbook ticket sent to you. Your movie ticket can be sent to Passbook directly via the Fandango app or via a link in Fandango's purchase confirmation email or SMS message.


20130201-01-PassbookSiri.jpg
With iOS 6.1, Siri, Fandango and Passbook collaborate to help you quickly find and purchase tickets to your movie.

Here are steps to get movie ticket :-

  1. You need to ask Siri "Where is the movie < Movie Name > playing".
  2. Siri responds by briefly showing you a list of nearby theaters playing < Movie Name > , and then shows the closest Theater and Show time. At the same time, Siri announces exactly how far away the Theater is and in what direction.

  3. 20130201-02-PassbookSiri.jpg
    Siri presents you with nearby theaters featuring your's requested movie.

  4. Siri then asks if you want to have her call the Theater, show the Directions to the theater, or skip to the next Theater featuring XYZ.
  5. By Tapping, you can select the theater. This allows to go on to purchase the ticket for the desired show time.
  6. Siri transfers you out to the Fandango app where u can complete your's purchase.

Finally, via the Fandango app confirmation page or Fandango's confirmation email or SMS, You can choose to have the movie ticket installed into your's Passbook for later use when you arrive at the theater.


20130201-03-PassbookSiri.jpg
Once the transaction is complete, your's movie ticket is ready to be scanned at the theater.

What is customer relationship management (CRM) system?



Looking into the increasing need of competition in the industry, a unique technology is required. With customer relationship management or CRM, you would be able to manage your business proceedings in a proper manner. As industries are cropping up in every part, use of this CRM system will help you in having a cutting edge to your business. With the use of this CRM system, you would be able to cater to all the needs and requirements of your customers in a hassle free manner. You can even save a lot on the expenses, which you may require to incur on maintaining the records of your business.

As customization is available with this software, you can customize it according to your needs and requisition. If you were willing to augment your customer service, then this software would be perfect for use. With use of CRM system, you would be able to process the appointments with accuracy. Record of every client availing your services can be kept in a proper and organized manner with use of CRM system. With this software, you would be able to maintain the records of your satisfied customers and improve on the quality and services taking use of the tips given by the customers.

Keeping a track of the engagements would be easy and convenient and you can even send your customers a reminder about the appointments, which they are having with you. This software would help you in managing your clients in a better manner.

Magento Integration Helps An E-Commerce Business To Attain Success

Magento is the most popular e-commerce platform that couldn’t be neglected ever. Although building an e-commerce site is not as easy as thought off, the length of its success varies. And it is the selection of the Magento integration modules that defines the technical muscle of an e-commerce site within a specified budget.

Magento e-commerce modules are divided into ten different categories like accountancy, CRM payment shipping, social media etc. All these categories have a high number of modules which are very useful and are proved to be highly advantageous, if used in accordance to the specific business needs. Considering CRM, Magento integration can provide you with different integration tools to connect to the CRM database. You can connect it to your entire CRM database or can opt for streamlined CRM functionalities like ‘Cloud Gento for sales force’ which will give you limited but coherent functionalities  saving a lot of development cost. 
 
The success of Magento integration can be defined by the free modules that are available across all the functional categories. Almost half of the modules in every category are free. As for example if we consider a social media  integration in Magento, we will find applications like Facebook products tab, post affiliate post connector and other free applications. These applications may come with lesser features but are highly specific in nature. On the other hand a developer may select the paid applications like social login from Magento integration store to create it more fancy e-commerce site which will allow the users to log into the e-commerce site with Facebook or Google applications. But the capability and the flexibility of an e-commerce site that you can enjoy with Magento varies vividly.

Struts2 - Dependency Injection and Inversion of Control

Struts2 - Dependency Injection and Inversion of Control

Dependency injection is a phenomena of configuring object in which fields of objects and collaborators are set by an outside entity. Clearly we can say an external entity configures objects. It can be said as an alternative procedure to configure the object by itself. Let us go through a simple example to understand this.

public class MyDaoObject
{
protected DataSource datasourceObject =new DataSourceImpl("driver","url","user","password");
//methos to access data
public Employee readEmployee(int primaryKey){...}
}

In the above Data Access Object (DAO) class, MyDaoObject, using an instance of javax.sql.DataSource in order to get connections to the database. For Employee object instance, connections to the database are used to write the data to the database and read from the database.

You might have notice that how MyDaoObject class instantiates a instance of DataSourceImpl as the DataSource required. Here the truth is that the MyDaoObject class requires a DataSource implemenation by which it is depending on it. It is not possible to complete its work without implementation of DataSource. Hence, MyDaoObject has a DataSource interface "dependency" and it is depending on some implementation of it.

This explains how coupling is going on objects. we can say dependency or coupling is the level to which two or more program module or objects relies on each other.

Now Let us come back to the dependacy injection and Inversion of control.Dependacy Injection (DI) and Inversion of Control are the design patterns, by using which we can reduce the dependancy or coupling in our programs. Dependancy Injection and Inversion of Control follows the two principles given below:

You do not need to Create Objects. You have to describe how they should be created.There is no need to instantiate or locate directly the services required by components. Instead of which we have to describe which services are required by which components.

Aware Interfaces in Struts2

When a HTTP specific object is required in Action, Dependancy Injection and Inversion of control is used in Struts 2. For this technique some interfaces known as aware interfaces will be injected into the action class. These interfaces are known as aware Interfaces. These Interfaces names will ends with Aware, that is why theses are known as aware Interfaces. Aware Interfaces contains methods to set specific resources into the action class.

In Struts 2 Dependancy Injection pattern impements the required interface, which exposes some methods to the action class.

Some of the aware interfaces which supports Struts 2

  • Application Interfaces
  • SessionAware Interface
  • ParameterAware Interface
  • ServletRequestAware Interface
  • ServletResponseAware Interface

ApplicationAware Interface

Package - org.apache.struts2.interceptor
Use - To expose a method to action class which sets an Application Map object in action class.
Methods - setApplication() which sets the map of application attributes in class.

Sample implementation of ApplicationAware interface

package yusata;
import java.util.Map;
import org.apache.struts2.interceptor.ApplicationAware;
import com.opensymphony.xwork2.ActionSupport;

public class ApplicationAwareAction extends ActionSupport implements ApplicationAware
{

private static final long serialVersionUID = 1L;
Map aps;
@Override
public void setApplication(Map aps) {
// TODO Auto-generated method stub
this.aps=aps;
}

public String execute() throws Exception
{
aps.put("name", "struts 2 blog");
return SUCCESS;
}
}

All key / value pairs which are stored in Application Map can be accessed from any JSP page.Struts2 jsp tags support the display of different application scope using corresponding key.

Example

< s:property value="#application.name"/>
or
< s:property value="#application['name']"/>

SessionAware Interface

Package - org.apache.struts2.interceptor
Use - is used handle the client session with in our action Action.
Methods - setSession() which sets the map of session attributes in class.This interface can access the session attributes in the action class.

Sample implementation of SessionAware interface

package yusata;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public class SessionAwareSample extends ActionSupport implements SessionAware
{
Map sessions;
@Override
public void setSession(Map sessions) {
// TODO Auto-generated method stub
this.sessions=sessions;
}
public String execute() throws Exception{
sessions.put("id", "JAVA STUDY CHANNEL.. learn over a cofee");
return SUCCESS;
}
}

The single key /value pair stored in session Map session can be accesses in a JSP as shown below.

Example

< s:property value="="#session.id"/>
or
< s:property value="="#session['id']"/ >

ParameterAware Interface

Package - org.apache.struts2.interceptor
Use - is used when input parameters are to be handled by the Action Class.
Methods - setParameters() which sets the map of parameter attributes in class.This interface can access the session attributes in the action class.
all the parameters for a given name will return a string data,so the type os object data in the Map is String[].

Sample implementation of ParameterAware interface

package yusata;
import java.util.Map;
import org.apache.struts2.interceptor.ParameterAware;
import com.opensymphony.xwork2.ActionSupport;

public class SessionAwareSample extends ActionSupport implements ParameterAware
{
Map params;
@Override
public void setParameters(Map params) {
// TODO Auto-generated method stub
this.params=params;
}

public String execute() throws Exception
{
return SUCCESS;
}
}

The parameter Map contains all the input values and the action class can use this map to process input parameters.

Example

< s:property value="#parameters.id"/>
or
< s:property value="#parameters['name']"/ >

ServletRequestAware Interface

The HttpServletRequest object is not acilable in the action.But this can be injected in the action class with ServletRequestAware Interface.

Package - org.apache.struts2.interceptor
Use - is allows an action to use HttpServletRequest in a servlet environment.
Methods - ServletRequest(HttpServletRequest reqt)

Sample implementation of ServletRequestAware interface

package yusata;
import java.util.Map;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionAwareSample extends ActionSupport implements ServletRequestAware
{
HttpServletRequest reqt;

@Override
public void setServletRequest(HttpServletRequest reqt) {
// TODO Auto-generated method stub
this.reqt=reqt;
}

public String execute() throws Exception
{
reqt.setAttribute("site","strtus 2 blog");
HttpSession session=reqt.getSession();
return SUCCESS;
}
}

ServletResponseAware Interface

The ServletResponseAware Interface is similar to the ServeletRequestAware interface except that object is injected HttpServletResponse action.

Package - org.apache.struts2.interceptor
Use - is allows an action to use HttpServletResponse in a action class.
Methods - ServletResponse(HttpServletResponse resp)

Sample implementation of ServletResponseAware interface

package yusata;
import java.util.Map;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletResponse;
public class SessionAwareSample extends ActionSupport implements ServletResponseAware
{
HttpServletResponse resp;
@Override
public void setServletResponse(HttpServletResponse resp) {
// TODO Auto-generated method stub
this.resp=resp;
}

public String execute() throws Exception
{
resp.setContentType("text/html");
int buf=resp.getBufferSize();
return SUCCESS;
}
}

Capture signature in Android

Capture signature in Android

App is used to take signature and save for future reference. It have two layout activity_main.xml and signature.xml , two activity classes MainActivity.java, CaptureSignature.java.

activity_main.xml

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

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="20dp"
    android:text="@string/hello"
    android:textSize="25sp"
    android:textStyle="bold" />

<Button
    android:id="@+id/signature"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get My Signature" />

</LinearLayout>

signature.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="600dp"
    android:layout_height="400dp"
    android:orientation="vertical" >

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

<Button
    android:id="@+id/cancel"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_weight=".30"
    android:text="Cancel" />

<Button
    android:id="@+id/clear"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_weight=".35"
    android:text="Clear" />

<Button
    android:id="@+id/getsign"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_weight=".35"
    android:text="Save" />

</LinearLayout>

<TableLayout
    android:id="@+id/tableLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:paddingLeft="10sp"
    android:text="Your Name"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/yourName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:maxLength="30" >
    <requestFocus />
</EditText>
</TableRow>

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLength="30"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLength="30"
    android:text="Please Sign below ..."
    android:textAppearance="?android:attr/textAppearanceMedium" />

</TableRow>
</TableLayout>

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java

package com.example.capturesignature;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

public static final int SIGNATURE_ACTIVITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getSignature = (Button) findViewById(R.id.signature);
getSignature.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,CaptureSignature.class);
startActivityForResult(intent, SIGNATURE_ACTIVITY);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SIGNATURE_ACTIVITY:
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String status = bundle.getString("status");
if (status.equalsIgnoreCase("done")) {
Toast toast = Toast
.makeText(this, "Signature capture successful!",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 105, 50);
toast.show();
}
}
break;
}
}
}

CaptureSignature.java

package com.example.capturesignature;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CaptureSignature extends Activity {
LinearLayout mContent;
signature mSignature;
Button mClear, mGetSign, mCancel;
public static String tempDir;
public int count = 1;
public String current = null;v private Bitmap mBitmap;
View mView;
File mypath;
private String uniqueId;
private EditText yourName;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.signature);
tempDir = Environment.getExternalStorageDirectory() + "/"
+ getResources().getString(R.string.external_dir) + "/";
Log.i("info", "tempDir "+tempDir);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(
getResources().getString(R.string.external_dir),
Context.MODE_PRIVATE);
prepareDirectory();
uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_"+ Math.random();
current = uniqueId + ".png";
mypath = new File(directory, current);
Log.i("info", "mypath "+mypath);
mContent = (LinearLayout) findViewById(R.id.linearLayout);
mSignature = new signature(this, null);
mSignature.setBackgroundColor(Color.WHITE);
mContent.addView(mSignature, LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
mClear = (Button) findViewById(R.id.clear);
mGetSign = (Button) findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button) findViewById(R.id.cancel);
mView = mContent;
yourName = (EditText) findViewById(R.id.yourName);
mClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Saved"
); boolean error = captureSignature();
if (!error) {
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
Bundle b = new Bundle();
b.putString("status", "done");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
}
});
mCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
});
}

@Override
protected void onDestroy() {
Log.w("GetSignature", "onDestory");
super.onDestroy();
}

private boolean captureSignature() {
boolean error = false;
String errorMessage = "";
if (yourName.getText().toString().equalsIgnoreCase("")) {
errorMessage = errorMessage + "Please enter your Name\n";
error = true;
}
if (error) {
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 105, 50);
toast.show();
}
return error;
}

private String getTodaysDate() {
final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000)+ ((c.get(Calendar.MONTH) + 1) * 100)+ (c.get(Calendar.DAY_OF_MONTH));
Log.w("DATE:", String.valueOf(todaysDate));
return (String.valueOf(todaysDate));
}

private String getCurrentTime() {
final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
Log.w("TIME:", String.valueOf(currentTime));
return (String.valueOf(currentTime));
}

private boolean prepareDirectory() {
try {
if (makedirs()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this,"Could not initiate File System.. Is Sdcard mounted properly?",1000).show();
return false;
}
}

private boolean makedirs() {
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory()) {
File[] files = tempdir.listFiles();
for (File file : files) {
if (!file.delete()) {
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}

public class signature extends View {
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();

public signature(Context context, AttributeSet attrs) {

super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}

public void save(View v) {
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(mContent.getWidth(),mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
Log.v("log_tag", "url: " + url);

} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}

public void clear() {
path.reset();
invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}

private void debug(String string) {
}

private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}

private void resetDirtyRect(float eventX, float eventY) {
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.capturesignature"
    android:versionCode="1"
    android:versionName="1.0" >

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

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
<activity
    android:name=".MainActivity"
    android:label="@string/title_activity_main" >
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
    android:name=".CaptureSignature"
    android:label="@string/title_activity_main" >
</activity>
</application>

</manifest>

After make these classes in your project just run it You will see this as below:



How to get movement speed from iPhone/iPad device ?

How to get movement speed from iPhone/iPad device ?

Sometimes it is required to get speed from UIDevice to fulfill certain tasks. To calculate speed of iOS devices like iPhone/iPad you can use CLLocationManager delegates. To use this you should to add a few things in your application.

Here are steps to measure or calculate speed

  • Add CLLocationManagerDelegate in interface file declaration.
  • Create CLLocationManager object
  • After this you should use following lines in implementation file mainly in
    -(void)viewDidLoad method


CLLocationManager *locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[loactionManager startUpdatingLocation];

Now following delegates of CLLocationManager can be used

(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation*)newLocation

fromLocation:(CLLocation *)oldLocation{
//simply get the speed provided by the phone from newLocation
double gpsSpeed = newLocation.speed;
NSLog(@"Speed of Device is %f",newLocation.speed);
// alternative manual method
if(oldLocation != nil)
{
CLLocationDistance distanceChange = [newLocation getDistanceFrom:oldLocation];
NSTimeInterval sinceLastUpdate = [newLocation.timestamp
timeIntervalSinceDate:oldLocation.timestamp];
double calculatedSpeed = distanceChange / sinceLastUpdate;
}
}

Above code works fine when device travels over a large area.

If you want calculated or measured speed in KPH then you have to multiply the measured speed by 3.6.

If you want speed in MPH then multiply it with 2.23693629 for MPH.

Background Location reporting in iOS

Background Location reporting in iOS

Upon working on location product, one of the little challenges along the way has been how to report background location updates back to our servers.
First, some basics.
We're going to be using the Significant Location Changes feature as this is the recommended way of tracking the approximate device location in a low power way.
Note the really key features here;
a) If the application is suspended when an update occurs, the system wakes it up in the background to handle the update.
b) If the application starts this service and is then terminated, the system relaunches the application automatically when a new location becomes available.
That's just perfect, so what we can now do is turn on significant location updates when the user hits the home key and we can let the system wake us up when needed.


-(void) applicationDidEnterBackground:(UIApplication *) application
{
// You will also want to check if the user would like background location
// tracking and check that you are on a device that supports this feature.
// Also you will want to see if location services are enabled at all.
// All this code is stripped back to the bare bones to show the structure
// of what is needed.

[locationManager startMonitoringSignificantLocationChanges];
}
Then to perhaps switch to higher accuracy when the application is started up, use;

-(void) applicationDidBecomeActive:(UIApplication *) application
{
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}

Next we'll likely want to change your location manager delegate to handle background location updates.

-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}

// Handle location updates as normal, code omitted for brevity.
// The omitted code should determine whether to reject the location update for being too
// old, too close to the previous one, too inaccurate and so forth according to your own
// application design.

if (isInBackground)
{
[self sendBackgroundLocationToServer:newLocation];
}
else
{
// ...
}
}

If we are running in the background, we can't just use the network as we would normally. In background mode the iOS controls very strictly what is allowed, and for how long it is allowed, so if we were just to send the location to our server as normal, we will find this will be highly unreliable. It may work sometimes, it may not, and you will have no control over what is going on. We can however TELL the operating system in advance that we are doing a background task that should be allowed to run to completion. By doing this, we can ensure that our network activity is given enough time to complete and so the remote server will get the location updates OK.


-(void) sendBackgroundLocationToServer:(CLLocation *)location
{
// REMEMBER. We are running in the background if this is being executed.
// We can't assume normal network access.
// bgTask is defined as an instance variable of type UIBackgroundTaskIdentifier

// Note that the expiration handler block simply ends the task. It is important that we always
// end tasks that we have started.

bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication} endBackgroundTask:bgTask];
}];

// ANY CODE WE PUT HERE IS OUR BACKGROUND TASK

// For example, I can do a series of SYNCHRONOUS network methods (we're in the background, there is
// no UI to block so synchronous is the correct approach here).

// ...

// AFTER ALL THE UPDATES, close the task

if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication} endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}

The key to this whole process is the use of background tasks to ensure that our synchronous network activity is given enough time to complete. This lets us update a couch database for example where we might need to make 1 network call to get the current document revision and then a second network call to actually put the new data.

Authorize.Net Integration into Java

Authorize.Net Integration into Java

The Merchant Interface at https://secure.authorize.net is a secure website where you can manage your payment gateway account, submit manual transactions, monitor and review unsettled transactions, search for and view settled transactions, view account billing statements, configure account settings and more.

Authorize.Net can be integarted in your website using following steps :

1. Sign up for Test Account :

Sign up for a test account to obtain an API Login ID and Transaction Key. These keys will authenticate requests to the payment gateway.

2. Install the Authorize.Net SDK:

Download anet-java-sdk-1.4.2.jar and place into your project library files.

3. Create the page that will host the form that will be submitted:

This method is implemented via three code snippets. First, create the page that will host the form that will be submitted. We're calling this purchaseForm.jsp, and you will be required to enter in your API_LOGIN_ID, TRANSACTION_KEY, and your public facing MERCHANT_HOST domain name. Note, you may want to alter the relayResponseUrl and place the jsp in a separate webapp container of your choice.

<%@ page import="net.authorize.sim.*" %>
<%
String apiLoginId = "YOUR_API_LOGIN_ID";
String transactionKey = "YOUR_TRANSACTION_KEY";
String relayResponseUrl = "http://MERCHANT_HOST/Authorizerelay_response.jsp";

String amount = "2.25";
Fingerprint fingerprint = Fingerprint.createFingerprint(
apiLoginId,
transactionKey,
1234567890, // random sequence used for creating the finger print
amount);

long x_fp_sequence = fingerprint.getSequence();
long x_fp_timestamp = fingerprint.getTimeStamp();
String x_fp_hash = fingerprint.getFingerprintHash();
%>

<FORM NAME='secure_redirect_form' ID='secure_redirect_form_id'
ACTION='https://test.authorize.net/gateway/transact.dll' METHOD='POST'>
<label>CreditCardNumber</label><input type='text' class='text' name='x_card_num' size='15'></input>
<label>Exp.</label><input type='text' class='text' name='x_exp_date' size='4'></input>
<label>Amount</label><input type='text' class='text' name='x_amount' size='9' readonly value='<%=amount%>'></input>
<INPUT TYPE='HIDDEN' NAME='x_invoice_num' VALUE='<%=System.currentTimeMillis()%>'>
<INPUT TYPE='HIDDEN' NAME='x_relay_url' VALUE='<%=relayResponseUrl%>'>
<INPUT TYPE='HIDDEN' NAME='x_login' VALUE='<%=apiLoginId%>'>
<INPUT TYPE='HIDDEN' NAME='x_fp_sequence' VALUE='<%=x_fp_sequence%>'>
<INPUT TYPE='HIDDEN' NAME='x_fp_timestamp' VALUE='<%=x_fp_timestamp%>'>
<INPUT TYPE='HIDDEN' NAME='x_fp_hash' VALUE='<%=x_fp_hash%>'>
<INPUT TYPE='HIDDEN' NAME='x_version' VALUE='3.1'>
<INPUT TYPE='HIDDEN' NAME='x_method' VALUE='CC'>
<INPUT TYPE='HIDDEN' NAME='x_type' VALUE='AUTH_CAPTURE'>
<INPUT TYPE='HIDDEN' NAME='x_amount' VALUE='<%=amount%>'>
<INPUT TYPE='HIDDEN' NAME='x_test_request' VALUE='FALSE'>
<INPUT TYPE='HIDDEN' NAME='notes' VALUE='extra hot please'>
<INPUT TYPE='SUBMIT' NAME='buy_button' VALUE='BUY'>
</FORM>

4. Create a page, Called Authorizerelay_response.jsp :

which will receive the response. Once again, you will be required to enter in your API_LOGIN_ID and your public facing MERCHANT_HOST domain name. Additionally, you will have to provide your MD5_HASH_KEY. Unless you have explicitly set this in the merchant interface: Account > Settings > Security Settings > MD5-Hash, leave this as an empty string.

<%@ page import="java.util.Map" %> <%@ page import="net.authorize.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
var referrer = document.referrer;
if (referrer.substr(0,7)=="http://") referrer = referrer.substr(7);
if (referrer.substr(0,8)=="https://") referrer = referrer.substr(8);
if(referrer && referrer.indexOf(document.location.hostname) != 0) {
<%
String apiLoginId = "YOUR_API_LOGIN_ID";
String receiptPageUrl = "http://MERCHANT_HOST/ Authorizeorder_receipt.jsp";
/*
* Leave the MD5HashKey as is - unless you have explicitly set it in the
* merchant interface: Account > Settings > Security Settings > MD5-Hash
*/
String MD5HashKey = "YOUR_API_LOGIN_ID";

net.authorize.sim.Result result = net.authorize.sim.Result.createResult(apiLoginId,MD5HashKey, request.getParameterMap());
// perform Java server side processing...
// ...
// build receipt url buffer
StringBuffer receiptUrlBuffer = new StringBuffer(receiptPageUrl);

if(result != null) {
receiptUrlBuffer.append("?");
receiptUrlBuffer.append(ResponseField.RESPONSE_CODE.getFieldName()).append("=");
receiptUrlBuffer.append(result.getResponseCode().getCode());
receiptUrlBuffer.append("&");
receiptUrlBuffer.append(ResponseField.RESPONSE_REASON_CODE.getFieldName()).append("=");
receiptUrlBuffer.append(result.getReasonResponseCode().getResponseReasonCode());
receiptUrlBuffer.append("&");
receiptUrlBuffer.append(ResponseField.RESPONSE_REASON_TEXT.getFieldName()).append("=");
receiptUrlBuffer.append(result.getResponseMap().get(
ResponseField.RESPONSE_REASON_TEXT.getFieldName()));

if(result.isApproved()) {
receiptUrlBuffer.append("&").append(ResponseField.TRANSACTION_ID.getFieldName()
).append("=");
receiptUrlBuffer.append(result.getResponseMap().get(
ResponseField.TRANSACTION_ID.getFieldName()));
}
}
%>
// Use Javascript to redirect the page to the receipt redirect url. If Javascript is not
// available, then the <meta> refresh tag will handle the redirect.
document.location = "<%=receiptUrlBuffer.toString()%>";
}
//-->
</script>
<noscript><meta http-equiv="refresh" content="0;url=<%=receiptUrlBuffer.toString()%>">
</noscript>
</body>
</html>

5. Create a page, called Authorizeorder_receipt.jsp:

which will host the receipt information.

<%@ page import="java.math.BigDecimal" %> <%@ page import="java.util.Map" %> <%@ page import="net.authorize.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<h1>Your Receipt Page</h1></br>
<%
// Show the confirmation data
Map<String, String[]> requestParameterMap = request.getParameterMap();

if(requestParameterMap != null && requestParameterMap.containsKey(ResponseField.RESPONSE_CODE.getFieldName())) {
String transactionId = "";
if(requestParameterMap.containsKey(ResponseField.TRANSACTION_ID.getFieldName())) {
transactionId = requestParameterMap.get(ResponseField.TRANSACTION_ID.getFieldName())[0];
}

// 1 means we have a successful transaction
if("1".equals(requestParameterMap.get(ResponseField.RESPONSE_CODE.getFieldName())[0])) {
%>
<h2>Success!</h2>
<h3>Your transaction ID:</h3>
<div><%=net.authorize.util.StringUtils.sanitizeString(transactionId)%></div>
<%
} else {
%>
<h2>Error!</h2>
<h3><%=net.authorize.util.StringUtils.sanitizeString(
requestParameterMap.get(ResponseField.RESPONSE_REASON_TEXT.getFieldName())[0])%></h3>
<table>
<tr>
<td>response code</td>
<td><%=net.authorize.util.StringUtils.sanitizeString(
requestParameterMap.get(ResponseField.RESPONSE_CODE.getFieldName())[0])%></td>
</tr>
<tr>
<td>response reason code</td>
<td><%=net.authorize.util.StringUtils.sanitizeString(
requestParameterMap.get(ResponseField.RESPONSE_REASON_CODE.getFieldName())[0])%></td>
</tr>
</table>
</div>
<%
}
}
%>
</body>
</html>

6. Verify the transaction is processed:

Upon loading purchaseForm.jsp and following the steps, you should have been able to successfully enter in your credit card information hit submit and receive a success or error message that is hosted on your merchant server.