Skip to main content

Posts

Showing posts from 2012

JSON to Apex Convesion simpler now with http://json2apex.herokuapp.com

With the REST API being lot used when integrating apps developed on force.com paltform with the mobile applications or integrating force.com with external applications communicating using JSON it becomes vital to know few of open source tool we have to make our task simpler.

When we are in technology consulting world the time becomes crucial in any project we face .
There are couple of tools that i normally use whenever an integration is using REST API and the format of data communication is in the form of JSON .
In this blog i will describe two commonly used applications that makes life simpler when dealing with the JSON data.
1)http://jsonlint.com/
This application is very useful to format and Validate the JSON .All you need to do is input the JSON in the text box provided and click on Validate button to Validate the JSON .
JSON Lint is a web based validator and reformatter for JSON, a lightweight data-interchange format.
2)http://json2apex.herokuapp.com/
This was recently developed b…

Handling PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException exception in SFDC Callout

Recently i encountered an exception during making a Callout to the external service .Being an apex developer and unfamiliar with SSL concept much with no luck after googling i tried posting the question in stackexchange Stackexchange link.I am thankful to the Martin Peters for helping me on this .

Through this blog post i would like to document few points i learned on cause of this exception and also i will indicate the solution and resources we have that can help us to get rid of this exception
1)First way to identify this exception is if we try to open the URL we are using to  make a callout to external system in any browser we will encounter the security exception.The below image shows how our browser will behave once encountering such SSL exception.

2)This happens when the external system we make callout from the salesforce does not have valid SSL certificate 
For the JAVA client we have solution on the discussion board .http://boards.developerforce.com/t5/General-Development/PKI…

Oauth 2.0 Salesforce Using REST Console of Chrome Browser

Earlier in one of my blog post i had demonstrated on how to use Mozilla Poster tool to verify the REST API calls of the salesforce.

Using Chrome REST console has several advantages than poster mozilla .The response can be seen in both JSON and XML and also the concept of oauth 2.0 also can be practically understood .

There are very good articles on 2.0 on the developer.force.com and here is the link Digging deeper into Oauth 2.0

The workbench.developerforce.com has an excellent REST utility which helps in quick verification of Restful Apex services or even standard REST API exposed by the salesforce .One major disadvantage of this is since the oauth happens automatically the conceptual knowledge on how oauth 2.0 works is hidden .

In this blog post we will use the REST Console of the chrome and first get the oauth token from the salesforce instance and then will invoke the REST service from the salesforce .

Step 1-Getting oauth token from salesforce instance 

First step is to set up th…

Writing Test Classes For Apex Rest Service

I came across a question in a developer community on how to write Unit Test Classes for the Rest API service for POST HTTP calls

Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .

Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)


In one of my previous blog post i demonstrated how to use native parsing technique for Rest api for User Defined Type
I wrote the Test class for the same and this post is helpful for all those searching for how to write test classes for apex rest service annotated with POST Call
Here is the Rest Service Class for which i attempted the test class
@RestResource(urlMapping='/DemoUrl/*') global with sharing class MyRestResourcedemo { global class RequestWrapper{ public Account acct; public Contact[] cons; } global class ResponseWrapper { public String StatusCode; …

Sending Document as an attachment in the form of Pdf Using Workflow Rules of force.com platform and Visualforce Template feature

Emailing the pdf on click of a boolean check box or click of a button are frequent requirements for which we often think of using Triggers and using Outbound Emails of apex .

This requirement can be easily accomplished through workflow rules and the Visualforce Email Templates

In this blog POST will walk through on how to approach this

Step 1:
Creation of Email Field This is the first step to create an Email Field so that when we develop workflow rules when for the email alert the Recipient Type is asked we may fill in the email field
Step 2:
Creation of workflowThis is a simple step where based on business criteria draft a workflow rule.Usually rule should be to trigger the email alert only if the boolean flag is checked .
Step 3:Creation of email template The email Template will be a visualforce template and hence if you are familiar with visualforce this must be a straight forward impementation
Below is the sample code that you may customize by replacing with your relevant obje…

Native Parsing Of JSON input into User Defined Class through Apex Rest Service

I have walked into Apex Guide of SFDC to find if there are code samples for the parsing of the JSON into User defined Class in apex.Unfortunately document mentions that this can be achieved but still there were no code snippets i could find.

This blog post might help for small snippet reference to understand how we can write an apex class and structure the Constructor of the POST annotated method to achieve native parsing automatically.
Here is the Code Snippet of the Class . Note that the Request is a combination of Account and Contacts and hence we may need an inner class .

@RestResource(urlMapping='/DemoUrl/*') global with sharing class MyRestResourcedemo{ //User defined Class global class RequestWrapper{ Account acct; Contact[] cons; } //Response Wrapper Class global class ResponseWrapper{ public String StatusCode; public String StatusMessage; public Account acct; public Contact[] cons; } @HttpPost global static ResponseWrapper doPost(RequestWrapp…

How to attach an image as an attachment to the parent object using REST API of force.com when image come from client as base64 encoded Text in JSON request

The REST API's offered by the force.com platform has matured lot since previous three versions and this makes it exiting for the integration with other system supporting JSON in their API's
I was reading an article by Sandeep Bhanot(I personally feel he is one of the best in salesforce evangelism) on the platform's ability to deserialise the base 64 encoded image and also decode it .
Here is the link to the article Using Binary Data With REST
Unfortunately my client app(ipad app)was using older version of REST kit that comes along with SDK and they feared upgrading to the newer version
Hence the design was altered to pass the base64 encoded text in the JSON request.Following is the code snippet that we need to decode the binary base 64 encoded image and attach as an attachment to the necessary parent object in sfdc
@RestResource(urlMapping='/Callmanagement/v1/*') global with sharing class SFA_DoctorsignPoc { @HttpPost global static String attachdoctorsSign(Str…

Tips On Passing Advanced Developer Salesforce Certification(501) multiple Choice Questions

I am glad to share that i cleared Advanced Developer first round .There are already good number of blogs on how to approach this exam.

Following blogs are really good resource and also they give a fair amount of idea on how to approach and how to clear this exam.

1)http://blog.jeffdouglas.com/2009/07/13/i-passed-the-salesforce-com-certified-advanced-developer-exam-so-can-you/
2)http://corycowgill.blogspot.in/2011/05/passing-forcecom-advanced-developer-501.html
3)http://exploresalesforce.blogspot.in/2012/01/how-to-clear-dev-501-exam.html
4)http://www.laceysnr.com/2011/12/five-oh-one-part-one-advanced-developer.html
5)http://limitexception.herod.net/2011/12/14/helping-you-pass-your-501-advanced-developer-exam/

Now my aim is to provide some more points on how to go about it.Please dont refer any dumps or ask for dumps as it is not the purpose of examination .

1)Dont jump into the exam as soon as you clear DEV-401 (developer certification)
2)If you are a developer on the platform and extensiv…

New ID.getSObjectType Method in Apex version 26 (Part of winter 13 release)

While i was going through winter 13 release notes of salesforce one of the interesting feature i found was addition of new method ID.getSObjectType.
This will be very helpful in getting the object token without making one more describe call if already in the code we have the List of ID's or ID.
Here is the small snippet i ran in new enhanced developer console(Pretty excited about this new console)
Id accid=[Select Id from Account Limit 1].ID; Schema.Sobjecttype inspecttype=accid.getSObjectType(); system.debug('Object Token '+inspecttype); 23:33:30:025 USER_DEBUG [3]|DEBUG|Object Token Account As seen above this method works great if your sandbox has been updated
Also this method will help in methods where only primitive types can be passed as a parameter like @future where parameter cannot be sObject.

Chaining of Batches in APEX no more pain

Starting a Batch Job from Another Batch Job You can now start a batch job from another batch job by calling Database.executeBatch from the finish method of the batch class. This allows you to link your batch jobs and create a chain of jobs. Note that the governor limits of batch jobs still apply. This change applies to batch Apex saved using Salesforce.com API version 26.0 and later. Previously, with Apex saved using Salesforce.com API version 25.0 and earlier, you couldn’t call Database.executeBatch from within any batch Apex method. The version used is the version of the running batch class that starts another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job, the Salesforce.com API version of the helper class doesn’t matter.

Importance of Virtual Keyword in Apex and when to use Virtual keyword

I have less experience on Java Programming and hence posting this for all those who are familiar with basics of apex but unfamiliar with OOPS concepts like inhertience and polymorphism of JavaProblem description:I knew that the virtual keyword is used to extend a class and thanks to great documentation from salesforce.(http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_example.htm) But my problem is no where in document it is mentioned how to proceed if in my parent class there is a parameterized constructor .Example: global virtual class sobjectWrapper{ sobject sobjectDetails; String RefreshFlag=''; public sobjectWrapper(sobject r){ sobjectDetails=r; } } As seen in the above code there is a parametrised constructor.First i attempted to write the extended the class as shown below global class extutilility extends sobjectWrapper{ sobject sobjectDetails; String RefreshFlag=''; private string abc; extutilility(sobject r){ sobjectDetails=r } } A…

How to generate a Listed JSON from multiple Salesforce Objects(say account and contact) and send data in JSON format to mobile client without nesting Using REST API

Sometimes there is a request for listed JSON .Say we have two objects Accounts and Contacts and we have requirement not to nest the response instead send as a collection with key for list of Accounts as Account and key for Contact as Contact.Below is the JSON format thats expected output, { "Accounts": [ { "attributes": { "type": "Account", "url": "/services/data/v25.0/sobjects/Account/001W0000006XDG9IAO" }, "CreatedDate": "2012-08-09T08:29:43.000+0000", "LastModifiedDate": "2012-08-09T15:24:42.000+0000", "IsDeleted": true, "Id": "001W0000006XDG9IAO" }, { "attributes": { "type": "Account", "url": "/services/data/v25.0/sobjects/Account/001W0…

Few Intresting Tips On Making a Field Mandatory On Visualforce Page

Inspecting the CSS of the salesforce and playing around a bit we can easily make a field look like a required field with the help of below snippetThe validation can be easily handled at the back end and a small code that will be helping is below if(is error){ ApexPages.addmessage(new ApexPages.Message(ApexPages.Severity.Error, 'Error Message.........')); } tag has to be added in the page to display the error to the user.

Handling Exceptions In REST API wrappers in salesforce and setting proper HTTP error in header of HTTP response sent from Salesforce

To set the proper error code in the response packet returned from salesforce there is default HTTP error code tableThe documentation of valid http error codes supported is in the http response is accessed on clicking below Documentation on HTTP error codesTo handle this in code here is a below simple example that demonstrates how to set the HTTP error codes in salesforce @RestResource(urlMapping='/Account/*') global with sharing class accountrest { @HttpGet global static Account getMerchandiseById() { RestRequest req = RestContext.request; RestResponse res=RestContext.response; Account result; String accId = req.requestURI.substring( req.requestURI.lastIndexOf('/')+1); try{ result =[SELECT Name,AccountNumber,NumberofLocations__c FROM Account WHERE Id = :accId]; } catch(exception e){ System.debug(e.getMessage()); res.statusCode=400;//clear that error was due to account ID missing and hence BAD request } return result; }

cloudy: Using POSTER mozilla tool to get oauth token and access the REST API of salesforce

Using POSTER mozilla tool to get oauth token and verifying response from REST API salesforce Please follow the following steps:


1)https://login.salesforce.com/services/oauth2/token Use this first as a request URL to get access token .Please use test.salesforce.com for sandbox

2)To obtain access token you must Use POST http call: In the payload use

grant_type=password&client_id=<your_client_id>&client_secret=<your_client_secret>&username=<your_username>&password=<your_password>

where client id,client secret you will get from your remote access settings and please append security token if you are making from unautorized IP range .Please use appropriate User Name and Password

3)Once you POST to the service you will get acess token .Please save that for future requests

4)Next in the header add following parameter and its value as  Name:Authorization Value:Bearer +oauthtoken obtained (Bearer space and your oauth_token)

5)Now once you add header in requ…