Monday, August 29, 2011

Paypal return url issue with missing GET parameters

just post one more parameter to paypal. see below :-

< input type="hidden" name="rm" value="2" >

According to the paypal Buy Now Buttons manual regarding the 'rm' hidden parameter. If set to “2” and if return is set, the buyer will be sent back to the return URL using a POST method, to which all available transaction variables will also be posted.

Handling Paypal Instant Payment Notification (IPN)

When you reach the payment detail page on paypal site and click the "Pay" button paypal will send a POST message to our server. Our script then send a confirmation back to paypal to verify this POST.
Here's that flow diagram again.

Paypal Checkout Process

Easy payments using Paypal IPN

There are several PHP scripts and classes to process PayPal payments using their native IPN (Internet payment notification) feature. Because the whole process is based on the data you need to send via a web form to the PayPal payment processor these script look very similar.
The payment / notification process is shown via the following graphic:
paypal payment validation process
Inside the form there are several required values to process a payment. PayPal gives the advice to post them all to get everything working. The following variables get some special attention:
business = your PayPal email address
cmd = single payments or subscription service (_xclick or _xclick-subscriptions)
return = the URL where the buyer get back after the payment is processed
cancel_return = the URL where the buyer get back if he has cancelled the payment
notify_url = the location where your IPN script is located
rm = how you need the data submitted from PayPal to your IPN script (1=get, 2=post)
currency_code = the currency you accept for your payment
lc = the country version of PayPal where your buyer is send to
There are much more variables, but we think that the other variables (product, order and shipment information) speak for themselves. Find a complete form provided with the example files.
To run some IPN enabled payment process we need a small script which will double check if the data which is send to the IPN script is valid according the data which is stored on the PayPal server. This feature is very important if your e-commerce accepts automatic payments.
The following code is able to check if the payment is valid against the PayPal server. Use this test to decide if the payment is valid or not.
$url = 'https://www.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i =&gt; $v) {
$postdata .= $i.'='.urlencode($v).'&amp;';
}
$postdata .= 'cmd=_notify-validate';
 
$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
} else {
$web['port'] = 80;
$ssl = '';
}
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);
 
if (!$fp) {
echo $errnum.': '.$errstr;
} else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");
 
while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
// yes valid, f.e. change payment status
} else {
// invalid, log error or something
}
}
As mentioned before there are some complete solutions available on the internet. If your e-copmmerce site doesn’t have a complex product catalog you should use some static code from the PayPal website. For this guide we checked the PHP toolkit provided by PayPal.
Code condition
The first thing I noticed the code is not very clean and is using a coding style which is based on older PHP versions (f.e. for systems using register globals = On)
Implementation
After some code clean-up it was possible to use the included file together with my shopping cart script. Static variables are defined in one central configuration file and dynamic files are posted via the form in your web application.
IPN features
This script is written to handle the IPN validation process with different methods: cURL, fsockopen, and libcURL. I tried only the fsockopen option because this method looks good to me and should work on almost every web platform.
Documentation
There is a “Readme” file with the information about the most important features. A complete guide is not included and the information about subscription payments is missing in all files and documents. If you decide to start with the original files you should check also the comments within the configuration and example files.
Example files
The included files are good enough to jump start your paypal payment application. All files are included for a single buy button and also for processing the payment f.e. for the items from a shopping cart. The bad thing is that the bad coding style makes it not easy to integrate the script into you own application if you’re an PHP beginner.
As mentioned before I included my own example files to this PayPal payment guide. If you have questions about this code please post them to our forum, we’re glad to help. Don’t forget the code is provided as it is and we’re not responsible for the functions and/or risks while using this code.Download the example code here.

Saturday, August 27, 2011

Scheduling automated backup using SQL server 2008


it is very important to take backups for the database files on regular basis. Microsoft SQL server 2008 made this task very easy. In this blog, I am going through step by step that will allow
  • Users to schedule the backup to be taken on a particular interval
  • Delete the backup copies after a certain period of time

Schedule the database backup

First I am going to tell you the steps required to schedule the backup. Login to Sql Management studio and connect to the required database. Now from the object explorer, make sure SQL server agent is running, if not start SQL server agent(Right click and press start).

1
Expand the Management Node from the object explorer, and then select the maintenance plan node. To schedule maintenance plan, you need to have “SYSADMIN” database role. If you dont see the maintenance node, make sure you have the necessary permission. 
2

Right click the maintenance plan and then select “new maintenance plan”.
3
Enter the maintenance plan name in the popup box (This can be any name that identifies your task for ). This will identify your backup plan and you should choose a relevant name that suits your plan.

4

Now you will be in the configuration page for the maintenance plan. . Note the marked area, these are the two areas you need to use for setting up the maintenance plan. The marked area in the right top will be used to configure the time that the plan executes. Choose a time so that the database is least used. The bottom left pane shows the tasks that can be utilized to create an sql maintenance plan. since explaining all of them is not in the scope of this document, I am going to explore only two of them.
5

Click on the calendar item shown in the right side top. This will bring the job schedule properties popup window that configure the execution time/frequency of the tasks. Configure the data carefully so that it suits your requirement. Usually database backups are taken daily basis. Make sure you are selecting proper time so that your database is least used. Click ok once you finish.

6
From the maintenance plan tasks pane in the left side, select the backup database plan, this will be used to take backups for the databases. Drag and drop backup database task to the right side(as shown in the diagram).

7.1

Double click on the backup database task, it will open up a new window that allows you to configure the database configuration for the backup. Here you configure the databases that you need to backup, then specify a location for the backup, specify the extension for the backup files etc.
From the pop up modal window, by clicking on “Databases” dropdown, you will be able to select the required databases. Also configure the file location, extension for the backup file etc.

9

Click ok once finished. Now backup plan configuration is over. The backup files will be created on the scheduled time to the mentioned folder. The name of the file will be created by appending the date so that you can identify the back up for a particular date.
Since the backup files are created frequently,… it is a good practice that you delete backup files after a certain period of time. For this you need to execute clean up task  along with the maintenance plan. You can configure the clean up task as follows.
From the left side pane, drag and drop maintenance cleanup task.
11

Double click on the dropped item inorder to edit the clean up properties. Here you need to specify the backup location, and file extension for the back up files and specify the age of the file. It is a good practice that you keep one month old data, and delete anything prior to one month. 
13

Once you click ok, then save the maintenance plan. You can either wait till the next execution time or execute it manually inorder to check whether everything is working fine.

J2ME Download File From Server (How To Download File in J2ME)


Here is the code that can download file from server in j2me


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

/**
*
* @author Yosia KN
*/
public class DownloadImage {

public void download(String urlPath, String pathFolder, String filename) throws IOException {
/*
* example :
* urlPath : http://yosiakn.lumbungilmu.com/1.png
* pathFolder : file:///E:/YADS/
* fileName : 1.png
*/
HttpConnection http = (HttpConnection) Connector.open(urlPath);
InputStream input = http.openInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
int ch;
while ((ch = input.read()) != -1) {
output.write(ch);
}
http.close();
FileConnection file = (FileConnection) Connector.open(pathFolder + filename);
file.create();
file.openOutputStream().write(output.toByteArray());
output.close();
file.setReadable(true);
file.close();
System.gc();
}
}



J2ME: How To Receive SMS in J2ME


i make sms which can receive by J2ME app, now, this is my sample code. it’s call J2ME push registry, so when i send sms, my J2ME app will launch automaticly
public class sampleSmsPushRegistry extends MIDlet
   implements CommandListener, Runnable, MessageListener {

   public void startApp() {
      smsPort = getAppProperty("SMS-Port");
      String smsConnection = "sms://:" + smsPort;
      if (smsconn == null) {
         try {
            smsconn = (MessageConnection)
               Connector.open(smsConnection);

            smsconn.setMessageListener(this);
         } catch (IOException ioe) {
            ioe.printStackTrace();
         }
      }
      display.setCurrent(resumeScreen);
   }
   public void notifyIncomingMessage(MessageConnection conn) {
      if (thread == null) {
         thread = new Thread(this);
         thread.start();
      }
   }
   public void run() {
      try {
         msg = smsconn.receive();
         if (msg != null) {
            if (msg instanceof TextMessage) {

               content.setString(((TextMessage)msg).getPayloadText());
            }
            display.setCurrent(content);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

}


How to send SMS in J2ME


The sample code on how to send SMS through J2ME.
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/** Sends an SMS message */
public class SMSender implements Runnable {
  private String smsReceiverPort;
  private String message;
  private String phoneNumber;

  public SMSender(String smsReceiverPort) {
    this.smsReceiverPort = smsReceiverPort;
  }

  public void run() {
    StringBuffer addr = new StringBuffer(20);
    addr.append("sms://+");
    if (phoneNumber.length() == 11)
      addr.append("86");//  china

    addr.append(phoneNumber);
    // String address = "sms://+8613641301055";
    String address = addr.toString();

    MessageConnection smsconn = null;
    try {
      // Open the message connection.
      smsconn = (MessageConnection) Connector.open(address);
      // Create the message.
      TextMessage txtmessage = (TextMessage) smsconn
          .newMessage(MessageConnection.TEXT_MESSAGE);
      txtmessage.setAddress(address);// !!
      txtmessage.setPayloadText(message);
      smsconn.send(txtmessage);
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (smsconn != null) {
      try {
        smsconn.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    }
  }

  public void send(String message, String phoneNumber) {
    this.message = message;
    this.phoneNumber = phoneNumber;
    Thread t = new Thread(this);
    t.start();
  }

}

J2ME Introduction


What is J2ME? Cut away the hype and the excess fat and you are left with yet another (set of) Java APIs. Since these APIs cannot run on a traditional Java Virtual Machine (JVM), due to the limited size of mobile devices in regards to memory and resource availability, J2ME defines a limited version of the JVM as well. In a nutshell:
J2ME combines a resource constrained JVM and a set of Java APIs for developing applications for mobile devices.
Do you, as a developer, have to install this JVM and the APIs on mobile devices? No. Device manufacturers install and prepackage their devices with this JVM (and associated APIs). As a developer, you only need to develop applications targeting these devices and install them. Easier said than done!
J2ME can be divided into three parts, as shown in Figure 1: a configuration, a profile, and optional packages. A configuration contains the JVM (not the traditional JVM, but the cut-down version) and some class libraries; a profile builds on top of these base class libraries by providing a useful set of APIs; and optional packages, are well, an optional set of APIs that you may or may not use when creating your applications. Optional packages are traditionally not packaged by the device manufacturers, and you have to package and distribute them with your application. The configuration and profile are supplied by the device manufacturers and they embedded them in the devices.
Figure 1
Figure 1. The J2ME stack
The most popular profile and configuration that Sun provides are the Mobile Information Device Profile (MIDP) and Connected Limited Device Configuration (CLDC), respectively. As the name suggests, CLDC is for devices with limited configurations; for example, devices that have only 128 to 512KB of memory available for Java applications. Consequently, the JVM that it provides is very limited and supports only a small number of traditional Java classes. (This limited JVM is actually called the KVM.) Its counterpart, the Connected Device Configuration (CDC) is for devices with at least 2MB of memory available and supports a more feature-rich JVM (but still not a standard JVM).
The MID profile complements the CLDC configuration very well because it minimizes both the memory and power required for limited devices. It provides the basic API that is used for creating application for these devices. For example, it provides the javax.microedition.lcdui package that allows us to create the GUI elements that can be shown on a (limited) device running the MID profile on top of a CLDC configuration. Note that MIDP cannot be used with CDC devices. CDC devices get their own set of profiles, like the Foundation and Personal profiles. However, I will not cover these profiles or the CDC here, and will concentrate on using MIDP and CLDC only.
The latest versions of MIDP and CLDC are 2.0 and 1.1, respectively. Not many devices currently support these versions, but the list is growing rapidly. Sun maintains a list of devices according to version.

J2ME-The MIDlet Lifecycle


The MIDlet Lifecycle

What happens if the AMS calls the destroyApp(boolean unconditional) method in the middle of an important step that the MIDlet may be doing, and may be loath to be destroyed? This is where the Boolean unconditional flag comes into the picture. If this flag is set to true, the MIDlet will be destroyed, irrespective of what the MIDlet is doing. However, if this flag is false, effectively, the AMS is telling the MIDlet that it wants the MIDlet to be destroyed, but if the MIDlet is doing something important, it can raise a MIDletStateChangeException, and the AMS will not destroy it just yet. However, note that even then, there are no guarantees that the MIDlet will not be destroyed, and it remains up to each device to decide how they should handle the request. If the device does honor the MIDlet's request, it may try and invoke the destroyApp(boolean unconditional) at a later stage.

Beginners Guide To J2ME


What is J2ME?
J2ME is a versions of Java or as Sun Microsystems puts an edition of Java that is deisgned for Mobile devices and other environments. J2ME developers use a JAVA compiler,WirelessToolKit, and a Obfuscator to preverify the classes, compile and package the classed in a JAR and JAD combination.

What Can J2ME Be Used For?
Java was orginaly started to deploy on mobile devices such as Star7 and thus J2ME returnsSun to these roots. J2ME is deployed on such mobile devices as handsets, PDAs, SmartPhones, and RIMs in the mobile sector. It also is deployed in other small resource environments such as DigitalTV/InteractiveTV(iTV/javaTV), Automobiles/Jets( ?Telemactics), and etc.

What is the Syntax Like?
J2ME is similar to Java in that it uses the same syntax with some slight modifications. Unlike general java or J2SE, J2ME is not standalone in nature and thus their is not main method but a different set of methods that form a standard midlet.

An Example of a Midlet
//must be saved as same name that JAd referrers to as .java extension
package com.shareme.moonbuzz.midp;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;



// @author Fred Grott 

public abstract class MoonBuzz extends MIDlet  implements CommandListener {
	
	private Command exitCommand = 
            new Command(Resources.getString
                    (Resources.ID_GAME_EXIT), Command.EXIT, 1);
	
	// Initializing local variables
	
	 private Display display = null;
	 private  SplashMenu splash;
	 private boolean isStarted = false;
	 public boolean isActive = false;
	 
	//

	public MoonBuzz() {
		
		
		Cache.numItemsPerLevelRec = Cache.setItemsPerLevel(3);
		Cache.numItemsPerPreferencesRec = Cache.setItemsPerPrefs(3);
		Cache.isPrefsInitialized = RecordStores.isPrefs(1);
		if (Cache.isPrefsInitialized=false){
		    Cache.isPrefsInitialized =        
                          RecordStores.intitializePrefsRMS(
                               Cache.shakeMe, Cache.soundMe, Cache.levelMe);
			Cache.isHighScoreInitialized = 
                            RecordStores.intitializeLevelRMS(Cache.zeroScore);
			
		}
		
		
	}
	//
	protected void startApp() throws MIDletStateChangeException {
		isActive = true;
		if (!isStarted) {
			
			if (display == null){
				display = Display.getDisplay(this);
			}
			isStarted = true;
		}
		
		
		Canvas canvas = createCanvas();
		Display.getDisplay(this).setCurrent(canvas);
		canvas.setCommandListener(this);
		canvas.addCommand(exitCommand);
	}
	//
	protected void pauseApp() {
		isActive = false;
	}
	//
	protected void destroyApp(boolean p0) throws 
                      MIDletStateChangeException {
		
		notifyDestroyed();
		
		isActive = false;
	}
	// @param dl
	  
	public void setDisplayable(Displayable dl){
		display.setCurrent(dl);
	}
	
	public abstract Canvas createCanvas();
	public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				notifyDestroyed();
			}
	}
}


Each application in J2ME has one class that is a midlet with the methods of startApp. pauseApp, and destroyApp.

A Visual Demo
Here is a simple Pong J2ME game demo as a jav applet which you can play to see how apps work in a mobile device such as a handset.

Pong Game on c55 Siemens handset

What is Needed To Get Started?
To start coding in J2ME you need a WirelessToolKit and a java Obfuscator for J2ME. You will also need emulators/sdk for the device you are targeting. Some developers will add an IDE and J2ME Ant extensions, such as Antenna or J2ME Polish, to this list but there is a light J2ME code editor in Sun's WirelessToolKit.

Common J2ME Problems
J2ME as implemented on cell phone devices does not properly call the pauseApp method in the midlet correctly and thus you have to check if the canvas isVisible within the midlet application. J2ME is commonly deployed to devices with different screen sizes and input methods and thus you need to adjust for this in using images and code detecting user input.

J2ME Polish can be used to handle the multitude of different J2ME devices.



Performance considerations
Code for performance. Here are some ways to code with the aim to achieve the best
performance:
* Use local variables. It is quicker to access local variables than to access class
members.
* Avoid string concatenation. String concatenation decreases performance and can
increase the application's peak memory usage.
* Use threads and avoid synchronization. Any operation that takes more than 1/10 of a
second to run requires a separate thread. Avoiding synchronization can increase
performance as well.
* Separate the model using the model-view-controller (MVC). MVC separates the
logic from the code that controls the presentation.


Reference document: Click here