Apex Toolkit for Salesforce

Saturday, July 16, 2011 by Aslam - The Alexendra
Hi All,
Its a long time since I last posted :). So i am back with something interesting and useful contents again.
Most of us known that whenever we want to connect with any salesforce org and do query the data with any langugae, salesforce gives us some toolkit like PHP toolkit, Java toolkit, Ruby Toolkit, Flex Toolkit etc. But what when we want to connect with a remote Salesforce instance within salesforce only, using native Apex language. People use many alternate to achieve it, some uses partner wsdl to generate apex or some uses javascript toolkit. But I find them not easy to use and not easy to setup and they did not fit in my need.
So I come up with my own Apex Toolkit for Salesforce :)




Its easy to install package. You can install it from here:
https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Priq

For successful connectivity to any remote instance one entry for that salesforce server TYPE must be there in your remote site setting. I have by default included in package (NA1 to NA7) server url for salesforce. You can add more like (CS1 - CS9, NA1 - NA11, AP1 - AP10). For example see the below screen shot how i added most likely used server instances in my remote site settings. There must be 20-25 possible entries at most in my opinion.



It is very easy to use with only simple some lines of code to login and do a query to remote instance as below:

SFConnectionController controller = new SFConnectionController();
LoginResult loginResult
= controller.login(username, password, securityToken);
Response response
= controller.query('select Name, Email, Phone, MailingCity, MailingCountry from Contact', loginResult);
for(Record row: response.data.records){
string Name
= row.getFieldValue('Name');
string Email
= row.getFieldValue('Email');
string Phone
= row.getFieldValue('Phone');
string MailingCity
= row.getFieldValue('MailingCity');
string MailingCountry
= row.getFieldValue('MailingCountry');
}


There is one demo page and controller in package which shows how to use this functionality.
SFConnectionDemo
SFConnectionDemoController

The toolkit is just a start and gives users facility to do login and do simple queries on objects. One can easily extend this for better version. If you want to contribute in this, i have shared this project as open source here:

http://code.google.com/p/apex-toolkit-for-salesforce/

Here is one running online demo which shows how this package works. Just give your developer/production org's username, password (or securityToken as well), and click on search button. It will fetch the contact records from your organization and will display in table below.

http://labsprojects-developer-edition.ap1.force.com/SFConnectionDemo

Hope you will like it :)
Mail me for any configuration or setup issues and for feedback.

Thanks
Aslam Bari

Authorize.Net Apex Library: Salesforce and Authorize.Net Integration

Saturday, May 28, 2011 by Aslam - The Alexendra
Hi All,
Recently I came across one requirement where end user wants an easy way to pay fixed amount online from Salesforce to third party something like Donate page. In one of my previous post i showed you how you can do that using Paypal. Here is that paypal solution:
http://techsahre.blogspot.com/2011/01/simple-paypal-integration-with.html

I was thinking to implement the same thing but this time end user wanted something simpler easy to use and easy to test solution. Then i found that 'Authorize.Net' is one of the good solution for this type of requirements. Then i created one simple ready to use online payment tool in salesforce using 'Authorize.Net' as payment gateway.



I found a good tutorial here in PHP how to make that here. I used the same idea and rebuild my Apex solution.

You can download the package from this link:
https://login.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t90000000PqIH

Before using the tool, you first need to follow some basic things:

1) For checking/testing the things you need first test accounts. Go to "test account" page on Authorize.Net and create one merchant account (Card Not Present).

2) Change your "login" and "transkey" variables in "AuthorizeDotNet" class with the merchant account's API login id and transaction id.

After that you can simply use VF page "DoPayment" to see how this works.
/apex/DoPayment



On click of submit you will get information about your transaction, if successful it will show you transaction id and success message. Otherwise will show error message.

Check out this easy cool stuff and give me feed backs as always.


Thanks
Aslam Bari

Generate Multi Sheet Excel File In Salesforce

Wednesday, May 25, 2011 by Aslam - The Alexendra
Hi All,
Recently I came across with a requirement where I need to generate excel file from SFDC data of some objects. Traditionally we do this by making csv file. But here the challenge was that i need to fetch data from multiple objects and make single Excel File with different Sheet (tabs), each sheet belongs to single object and contains that object data. So here is code, how i achieve it.

Here is the link you can download the code from :

SFMultiSheetExcelGenerator
http://www.aslambari.com/downloads/SFMultiSheetExcelGenerator.zip

The folder contains some VF pages and some classes. There is one demo VF page also which contains a button which generates the sample excel file with contacts and accounts data. You can see the working demo here:
https://labsprojects-developer-edition.ap1.force.com/MultiSheetExcelGenerateDemo

There is a component which is responsible to generate the excel data. You can see the sample code in "MultiSheetExcelGenerate.page" VF page. Here is the code , how you use this component:


<apex:page controller="MultiSheetExcelGenerate" sidebar="false" showHeader="false" contentType="application/vnd.ms-excel#myfile.xls">
<c:multisheetexcelcomponent datamodel="{!dm}" />
</apex:page>

Have a look and use the code as per your need and mail me with your valuable feed backs as always :)

Thanks
Aslam Bari

'Android To Case' : Android App to log Salesforce Case

Saturday, May 21, 2011 by Aslam - The Alexendra
Hi All,
Most of you may know "Web To Case" functionality of Salesforce. I have used the same concept and reuse that idea to make simple Android App, which works exactly same as "Web to case", so i called this app as "Android To Case".

Here is some screen shot how it will look like:

1) Initial Screen:



2) After Submit below screen will come:




The code and app is simple. Here is the main code as below:

package com.androidsfdc.androidtocase;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidToCase extends Activity {
/** Called when the activity is first created. */
private static final String ORGID = "00D###0###0###G";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn
= (Button) findViewById(R.id.submit);

btn.setOnClickListener(
new View.OnClickListener() {

public void onClick(View v) {
try {
EditText name
= (EditText) findViewById(R.id.contactName);
EditText email
= (EditText) findViewById(R.id.email);
EditText phone
= (EditText) findViewById(R.id.phone);
EditText subject
= (EditText) findViewById(R.id.subject);
EditText description
= (EditText) findViewById(R.id.description);
StringBuffer params
= new StringBuffer();
params.append(
"orgid=" + URLEncoder.encode(ORGID, "UTF-8"));
params.append(
"&name="
+ URLEncoder.encode(name.getText().toString(),
"UTF-8"));
params.append(
"&email="
+ URLEncoder.encode(email.getText().toString(),
"UTF-8"));
params.append(
"&phone="
+ URLEncoder.encode(phone.getText().toString(),
"UTF-8"));
params.append(
"&subject="
+ URLEncoder.encode(subject.getText().toString(),
"UTF-8"));
params.append(
"&description="
+ URLEncoder.encode(description.getText()
.toString(),
"UTF-8"));
String output
= excutePost(
"https://www.salesforce.com/servlet/servlet.WebToCase?encoding=UTF-8",
params.toString());
name.setText(
"");
email.setText(
"");
phone.setText(
"");
subject.setText(
"");
description.setText(
"");
Toast.makeText(getBaseContext(),
"Case is successfully Created!!!",
Toast.LENGTH_LONG).show();

}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}

public static String excutePost(String targetURL, String urlParameters) {
URL url;
HttpsURLConnection connection
= null;
try {
// Create connection
url = new URL(targetURL);
connection
= (HttpsURLConnection) url.openConnection();
connection.setRequestMethod(
"POST");
connection.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");

connection.setRequestProperty(
"Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty(
"Content-Language", "en-US");

connection.setUseCaches(
false);
connection.setDoInput(
true);
connection.setDoOutput(
true);

// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd
= new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response
= new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(
'\r');
}
rd.close();
return response.toString();

}
catch (Exception e) {

e.printStackTrace();
return null;

}
finally {

if (connection != null) {
connection.disconnect();
}
}
}
}


You only need to change "ORGID" with your organization id in the above code. And it will work for your developer/production org.

This application will be useful for such companies who want their customers to log cases directly from their Android mobiles natively. They can simply setup this application and ask their customers to install the app on their mobiles. And this is ready to use.

You can download the complete code from here:
http://www.aslambari.com/downloads/AndroidToCase.zip

Hope you like this app :) . Give me feedback what do you think.

Thanks
Aslam Bari

Salesforce Drag Drop MultiSelect List Using JQuery

Friday, May 13, 2011 by Aslam - The Alexendra
Hi All,
Recently i came across with one requirement where end user needs a multiselect picklist where he can drag drop items between two list in Salesforce. I searched for some good drag drop scripts over net and finally found best one which fits in my need. It is from thechriswalker.net and you can see that in action here.

So I used that jquery stuff and wrapped that in a re-usable VF component to make it more general. It is very simple to use and easy to embed in you VF page.
In your VF page you simply need to call the VF component as below syntax:

<c:sfdragdroplist list1="India;United States;France;Germany;Japan" outputfieldid="list_2_serialised">

The above syntax will make two list on screen drag and drop enabled. Source list will have counties given in "list1". This attribute contains the list of items separated by semicolon ";". You can directly hard code these items to component or you can also fetch from any object fields and make that semicolon separated (note: multiselect picklist already contains values as semicolon separated) and pass to component. For storing what user is selecting for your DB or later processing purpose you need to make one extra textfield (or hidden field) and provide that id in above component like "list_2_serialised"

<input id="list_2_serialised" name="list_2_serialised" value="{!list2FinalItems}" type="hidden">



You can download the complete code from this package url
https://login.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t90000000PpxL

You can see the working demo here
http://labsprojects-developer-edition.ap1.force.com/apex/DemoSFDragDropList

The above implementation is for simple list drag drop, one can extend it to make it more advance level to enable drag drop between two different tables or screens.

Hope this will be helpful for users!!!

Thanks
Aslam Bari

Making Related List without using Apex Class

Thursday, May 5, 2011 by Aslam - The Alexendra
Hi All,
Here i want to give some sample code to show you how to make RelatedList on your VF page without using any Apex Code. There are two solutions for this problem.

1) Using <apex:relatedlist>
Suppose you have standard Case object and have one custom child object named "Child__c" to case. Then you can show your relatedlist on vf page using below code.

<apex:page standardController="Case">
<apex:relatedList list="Childs__r"/>
</apex:page>

The list will be displayed on your page but it always gives "Action" column also with "Edit | Del" links. If you want to get rid off that then you need to do a little jquery trick to remove that. See the below code.

<apex:page standardController="Case">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>

<script>
$(document).ready(function(){
$('#Childs a').attr('target','_blank');
});
</script>

<style>
.pbButton{
display:none;
}
.actionColumn{
display:none;
}
</style>

<Div id="Childs">
<apex:relatedList list="Childs__r"/>
</Div>

</apex:page>

The main issue i found using above approach of making list is that it depends on fields selected on page layout for that relatedlist. If you have added 2 fields on your layout, your vf will also show two fields. If you remove that related list from layout, then your vf will show only default fields ( name) only. So, in some sitations this solution is not perfect. For that reason, here is another solution.

3) Using relations objects iteration and Standard Tags.
Here is the other way to achieve your related list on vf page:

<apex:page standardController="Case">
<apex:sectionHeader title="http://www.aslambari.com" subtitle="Related List Example"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!Case.Childs__r}" var="child">
<apex:column headervalue="Name"><apex:outputLink value="/{!child.id}">{!child.name}</apex:outputLink></apex:column>
<apex:column value="{!child.detail__c}"/>
<apex:column value="{!child.is_active__c}"/>
<apex:column value="{!child.createddate}"/>
<apex:column value="{!child.createdbyId}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Here is a working demo for above code sample:
http://labsprojects-developer-edition.ap1.force.com/apex/RelatedListSample?id=50090000000sW5q


The above way, you can customize your list as you want.

Hope It helps developers to find quick solution for related list.

Thanks
Aslam Bari

Salesforce Native DatePicker Year Extending Component

Saturday, April 23, 2011 by Aslam - The Alexendra
Hi All,
I developed one simple and useful component to extend Native Salesforce DatePicker. You all must aware of that we can't change Year list in datepicker and have to depend of salesforce native year list which is about -1 to +5 of current year. This is not useful on many situation like if i need to make one Date Of Birth field or any other date field where i need years range some high.



So i came up with simple component solution for this of your VF page. You simply need to include this in your VF page and use as following.

Sample Usage:
1) By using "lowerLimit" and "higherLimit"
<c:datepickerextend lowerlimit="10" higherlimit="15"/>
It will pick first year available in picker year list , for example 2010, and then add 10 earlier years to top of the picklist.
Same for higherLimit, it will pick last year available in picker year list, for example 2016, and then add 15 later years to bottom of the picklist.

2) By using "startYear" and "endYear
<c:datepickerextend startYear="1982" endYear="2020"/>
It will simply fill year list from 1982 to 2020.

Downloads
----------------------------------------------------
1) Component Code: Download from here
http://www.aslambari.com/datepick_extend/DatePickerExtend.txt

2) jQuery Lib: Download from here and save in static resource as datepicker_extend (You can you any jquery lib instead)
http://www.aslambari.com/datepick_extend/jquery-1.5.2.min.js

3) Demo Usage Code: Download from here
http://www.aslambari.com/datepick_extend/DemoUsageCode.txt


Working online demo:
You can view one simple demo, used following code:

<c:datepickerextend lowerlimit="10" higherlimit="5"/>

http://labsprojects-developer-edition.ap1.force.com/DatePickerExtendDemo


Provide your feedback as always. Enjoy !!!

Thanks
Aslam Bari