Monday, March 26, 2012

Json in Apex class and Visualforce

Serializing JSON from Apex 
Apex Class:

public with sharing class jsonAccount {
public string AccountNameList {get;set;}
 public jsonAccount() {
    list<Account> accList = [Select Id,Name From Account]; 
    System.debug(JSON.serialize(accList));
    AccountNameList = JSON.serialize(accList);
 }

}
Output:
USER_DEBUG [2]|DEBUG|[{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBXIA0"},"Id":"001U0000002LdBXIA0","Name":"GenePoint"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBYIA0"},"Id":"001U0000002LdBYIA0","Name":"United Oil & Gas, UK"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBZIA0"},"Id":"001U0000002LdBZIA0","Name":"United Oil & Gas, Singapore"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBaIAK"},"Id":"001U0000002LdBaIAK","Name":"Edge Communications"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBbIAK"},"Id":"001U0000002LdBbIAK","Name":"Burlington Textiles Corp of America"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBcIAK"},"Id":"001U0000002LdBcIAK","Name":"Pyramid Construction Inc."},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBdIAK"},"Id":"001U0000002LdBdIAK","Name":"Dickenson plc"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBeIAK"},"Id":"001U0000002LdBeIAK","Name":"Grand Hotels & Resorts Ltd"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBfIAK"},"Id":"001U0000002LdBfIAK","Name":"Express Logistics and Transport"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBgIAK"},"Id":"001U0000002LdBgIAK","Name":"University of Arizona"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBhIAK"},"Id":"001U0000002LdBhIAK","Name":"United Oil & Gas Corp."},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002LdBiIAK"},"Id":"001U0000002LdBiIAK","Name":"sForce"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000002bHvsIAE"},"Id":"001U0000002bHvsIAE","Name":"AAA Copr"},{"attributes":{"type":"Account","url":"/services/data/v24.0/sobjects/Account/001U0000005sN4LIAU"},"Id":"001U0000005sN4LIAU","Name":"Test BBB"}]
VisualForce Page:

<apex:page controller="jsonAccount">
<apex:form id="qsgFrm">
<apex:outputLink onclick="getAccountName();"> Click and Get the Account Using JSON</apex:outputLink>
</apex:form>
<script>
<script>
//JSON Code
var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
 var t = typeof (obj);
 if (t != "object" || obj === null) {
  // simple data type
  if (t == "string") obj = '"'+obj+'"';
  return String(obj);
 }
 else {
  // recurse array or object
  var n, v, json = [], arr = (obj && obj.constructor == Array);
  for (n in obj) {
   v = obj[n]; t = typeof(v);
   if (t == "string") v = '"'+v+'"';
   else if (t == "object" && v !== null) v = JSON.stringify(v);
   json.push((arr ? "" : '"' + n + '":') + String(v));
  }
  return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
 }
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
 if (str === "") str = '""';
 eval("var p=" + str + ";");
 return p;
};
// GETING ACCOUNT DETAILS
var jsonobj = {!AccountNameList};
//To convert an object to JSON, use JSON.stringify:
var json_text = JSON.stringify(jsonobj, null, 2);
//To convert a JSON string to a JS object, use JSON.parse:
var your_object = JSON.parse(json_text);

 function getAccountName() { 
 for(var f=0; f < your_object.length; f++) {
  var aID = your_object[f].Id;
  var aName = your_object[f].Name;
 }
}
</script>
</apex:page>

VisualForce Lookup

Customize CKEditor on Force.com

Close Popup and refresh parent window

Here is the sample code for it:

<apex:commandbutton action="{!save}" id="button" oncomplete="javascript:CloseAndRefresh()" value="Update"/>

and here is the java script function

<script language="JavaScript" type="text/javascript">
function CloseAndRefresh(){
window.opener.location.href="/{!$CurrentPage.parameters.id}";
      window.top.close();
   
  }
</script>

Refresh Parent Window from Popup

<script language="javascript" type="text/javascript"> 
if("{!$Request.success}" == "true") { 
parent.window.close(); 
alert('Please refresh the Contact page to view your changes.'); 
window.close(); } 
</script>

HTTP Callout from Apex Class

public class simpleHTTPCallOut {
public simpleHTTPCallOut(ApexPages.StandardController controller)
{
}
String ErrorMessage;
public void Login() {
 ErrorMessage='';
 final string baseUrl = 'https://login.salesforce.com/';
 final string username = 'test@test.com';
 final string password = 'test@123';
 Http h = new Http();
 HttpRequest req = new HttpRequest();
 req.setMethod('GET');
 req.setEndpoint(baseUrl + '?loginType=&un='+username+'&pw='+password);
 HttpResponse res = h.send(req);
  
 req.setEndpoint(baseUrl + 'apex/EndPOINTPAGE');
 res = h.send(req);
 if (res.getBody().indexOf('success=true')>-1) {
  system.debug('Success');
 } 
}
}

Friday, March 23, 2012

how to parse json in javascript

Example :
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.

Get URL Parameters (QueryStrings) using Javascript

function getQueryStringValue(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
The getQueryStringValue function is simple to use. Let's say you have the following URL:
http://www.themoderneducation.com?YourName=TME
and you want to get the "YourName" querystring's value:
var YourName_Value = getQueryStringValue('YourName');
alert(YourName_Value); // Result = "TME"

Cross-browser JSON Serialization in JavaScript

Assume we have a fairly complex JavaScript object defined using literal notation:
var obj1 = {
b1: true,
s1: "text string",
n1: 12345,
n2: null,
n3: undefined,
a1: [ 1,1,2,3,5,8, [13, 21, 34] ], 
o1: {a: [3, 2, 1],
b: {c: 42,d: [ 3.14, 1.618 ]}} };
 
We can access any of the object properties in a variety of ways:

obj1.s1; 
// returns "text string" obj1["n1"]; 
// returns 12345 obj1.a1[6][1]; 
// returns 21 obj1["o1"]["b"]["c"]; 
// returns 42
 
However, what if we need to store this object in a cookie?
What if we need to pass the object to a web services via an Ajax request?
What if that web service wants to return a modified version of the object?
The answer is serialization:
  • Serialization is the process of turning any object into a string.
  • De-serialization turns that string back into a native object.
Perhaps the best string notation we can use in JavaScript is JSON JavaScript Object Notation. JSON is a lightweight data-interchange format inspired by JavaScript object literal notation as shown above. JSON is supported by PHP and many other server-side languages (refer to json.org). There are two JSON methods in JavaScript:
  1. JSON.stringify(obj) — converts an JavaScript object to a JSON string
  2. JSON.parse(str) — converts a JSON string back to a JavaScript object
Unfortunately, very few browsers provide these methods. To date, only Firefox 3.5, Internet Explorer 8.0 and Chrome 3 beta offer native support. Some JavaScript libraries offer their own JSON tools (such as YUI) but many do not (including jQuery). However, all is not lost — JavaScript is flexible and we can implement the JSON stringify and parse methods whenever a browser requires them. At the top of our code, we will create a JSON variable that points to the native JSON object or an empty object if it is unavailable:
 var JSON = JSON || {}; 
The JSON.stringify code is a little more complex:
 // implement JSON.stringify serialization JSON.stringify = JSON.stringify || function (obj) {  var t = typeof (obj);  if (t != "object" || obj === null) {   // simple data type   if (t == "string") obj = '"'+obj+'"';   return String(obj);  }  else {   // recurse array or object   var n, v, json = [], arr = (obj && obj.constructor == Array);   for (n in obj) {    v = obj[n]; t = typeof(v);    if (t == "string") v = '"'+v+'"';    else if (t == "object" && v !== null) v = JSON.stringify(v);    json.push((arr ? "" : '"' + n + '":') + String(v));   }   return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");  } }; 
If JSON.stringify is not available, we define a new function that accepts a single obj parameter. The parameter can be a single value, an array, or a complex object such as obj1 above. The code examines the object type. Single values are returned immediately and only strings are modified to put quotes around the value. If an array or object is passed, the code iterates through every property:
  1. Strings values have quotes added.
  2. Child arrays or objects are recursively passed to the JSON.stringify function.
  3. The resulting values are added to the end of a json[] array as a "name : value" string, or just a single value for array items.
  4. Finally, the json array is converted to a comma-delimited list and returned within array [] or object {} brackets as necessary.
If your brain's aching, you'll be pleased to know that the JSON.parse code is much simpler:
 // implement JSON.parse de-serialization JSON.parse = JSON.parse || function (str) {  if (str === "") str = '""';  eval("var p=" + str + ";");  return p; }; 
This converts a JSON string to an object using eval(). Before you rush off to implement JSON serialization functions in all your projects, there are a few gotchas:
  • This code has been intentionally kept short. It will work in most situations, but there are subtle differences with the native JSON.stringify and JSON.parse methods.
  • Not every JavaScript object is supported. For example, a Date() will return an empty object, whereas native JSON methods will encode it to a date/time string.
  • The code will serialize functions, e.g. var obj1 = { myfunc: function(x) {} }; whereas native JSON methods will not.
  • Very large objects will throw recursion errors.
  • The use of eval() in JSON.parse is inherently risky. It will not be a problem if you are calling your own web services, but calls to third-party applications could accidentally or intentionally break your page and cause security issues. If necessary, a safer (but longer and slower) JavaScript parser is available from json.org.
I hope you find the code useful. Feel free to use it in your own projects. Resource files:

Serializing to JSON in jQuery

JSON-js - JSON in JavaScript.
To convert an object to JSON, use JSON.stringify:
var json_text = JSON.stringify(your_object, null, 2);
To convert a JSON string to a JS object, use JSON.parse:
var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

Ruby and Salesforce Integration with SOAP

Simple Paypal Integration with Salesforce (Step by Step)

Using Map In Your VF Pages

APEX CLASS:
 public class TestMapController{
    
     public map<string,integer> data {get;set;}
    
     public TestMapController(){
         data = new map<string,integer>();
         for(Account acc: [Select Id, Name, (Select Id, Name, Email from Contacts), Phone from Account]){
             integer count = data.get(acc.name);
             if(count != null)
                count++;
            else
                count = 1;
            data.put(acc.name, count);
        }
    }
}
VisualForce Page:
<apex:page controller="TestMapController">
 <apex:pageblock title="Map Usage On VF">
 <apex:pageBlockTable value="{!data}" var="d">
     <apex:column headerValue="Account Name">
         {!d}
     </apex:column>
     <apex:column headerValue="Duplicate Count">
         {!data[d]}
     </apex:column>
 </apex:pageBlockTable>
 </apex:pageblock>
</apex:page>

Related List without using Apex Class

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>
 
2) Using relations objects iteration and Standard Tags. 
<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> 

Showing Salesforce Images/Attachments on PHP/JSP page

Overlay Effect for VF form submit

Monday, March 12, 2012

How to check whether a record has been locked in the Approval Process

Simple Steps:
Step1 : Create a field (say FLAG) of type Checkbox. Set the default value to UNCHECKED.

Step2: In your Approval Process in the INITIAL SUBMISSION Action , create a Field Update. Update the FLAG to TRUE.

Step3: In your FINAL APPROVAL and REJECTION Actions, create a Field Update. Update the FLAG back to FALSE.

Step4: And done!!!! You can now find whether a record has been locked simply by checking the FLAG value. Be it in your Apex Class or Visualforce Page.

Unit Testing in Salesforce

Testing is a key and critical component to successful long term software development process. Salesforce.com strongly recommends using a test-driven development process which occurs at the same time as code development. Salesforce has very strong set of documentation. When I was learning salesforce unit testing, I realize that it is difficult to understand where to start read. Therefore, I summarized the unit testing for salesforce beginners to understand the basic aspects of unit testing.

There are few things to consider before you deploy or upload the code or package;
  • 75% of your Apex code must be covered by unit tests
  • All the tests must complete successfully
  • Every trigger has some test coverage (1%)
  • All classes and triggers must compile successfully
When you are writing a test class, you have to write test for Single Action, Bulk Action, Positive Behavior, Negative Behavior, and Restricted User.
    • Single Action :Test to verify that a single record produces the correct, expected result.
    • Bulk Action :  Test not only the single record case, but the bulk cases as well
    • Positive Behavior :  Verify that the expected behavior occurs through every expected permutation
    • Negative Behavior :  Verify that the error messages are correctly produced 
    • Restricted User :Test whether a user with restricted access to the sObjects used in     your code sees the expected behavior 
        Test Class can be defined @isTest annotation. Before the Winter 12' release we had only private test classes, but on Winter 12' release salesforce has given the chance to write public test classes as well. Salesforce has released the public test classes for expose common methods for data creation. It can be used to setting up data that the tests need to run against. Public test methods can be called from a running test but not from a non-test request.

        When you create a test method,
        • Use static
        • Use testMethod keyword 
        • Use void return type
        • No any arguments
        • No data changes performed in a test method
        • Don't send emails
        • Cannot be used to test Web service callout because web services are asynchronous and tests are synchronous.
          • The API for asynchronous test runs is a Beta release (Winter '12)
          • For More : Force.com Apex code Developer's Guide Page 153 
        The key methods to use in your unit tests are the system.assert() methods. There are three types of system.assert() methods.
        • System.assert(condition)
        • System.assertEquals(x,y)
        • System.assertNotEquals(x,y)
        For the security review, every test method must have at least one system.assert() method. We need use assert methods not only for the pass the security review but also as a best practice. It will be help us to keep track the failures of Apex classes or triggers.

        Real-time sandbox environments in Salesforce

        A sandbox is basically a replication of your Salesforce org you can use for development, testing, and training without disrupting your production environment. Sandboxes are completely isolated from your Salesforce production organization, so anything you do in your sandboxes will not affect your Salesforce production application, and vice-versa. Sandbox provides a set of tools that deliver real, tangible business benefits and it's not just for developers.
        If you make a mess of things, your "real" data and org is protected and your sandbox can be refreshed 29 days from its creation or from the last refresh. You can be created a sandbox in production environment;
        Setup > Administration Setup > Data Management > Sandbox
        There are three types of sandboxes available to Salesforce.com customers.

        Configuration-only sandbox

        Configuration-only sandboxes copy all your production organization's reports, dashboards, price books, products, apps, and customizations, but exclude all your organization's standard and custom object records, documents, and attachments.

        Developer sandbox

        Developer sandboxes are special configuration-only sandboxes intended for coding and testing by a single developer. They provide an environment in which changes under active development can be isolated until they are ready to be shared. Just like configuration-only sandboxes, developer sandboxes copy all application and configuration information to the sandbox.

        Full sandbox

        Full sandboxes copy your entire production organization and all its data, including standard and custom object records, documents, and attachments.

        Javascript with Visualforce pages

        VISUALFORCE and JS CODE:
        <apex:page>
        <script>
        function changeFont(input, textid) {
        if(input.checked) document.getElementById(textid).style.fontWeight = "bold";
        else document.getElementById(textid).style.fontWeight = "normal";
        }
        </script>

        <apex:outputPanel layout="block">
        <label for="checkbox">Click this box to change text font: </label>
        <input id="checkbox" type="checkbox"
        onclick="changeFont(this,'{!$Component.thePanel}');"/>
        </apex:outputPanel>
        <apex:outputPanel id="thePanel" layout="block">Change me!
        </apex:outputPanel>
        </apex:page>
        Note:
        '{!$Component.idName}' : This is the way of passing particular visualforce component id into the javascript.

        Inline Editing in Visualforce page

        VISUALFORCE CODE:
        <apex:page standardController="Contact">
        <apex:form >
        <apex:pageBlock mode="inlineEdit">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!edit}" id="editButton" value="Edit"/>
            <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
            <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:outputField value="{!contact.lastname}">
                <apex:inlineEditSupport showOnEdit="saveButton, cancelButton"
                    hideOnEdit="editButton" event="ondblclick"
                    changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
            </apex:outputField>
            <apex:outputField value="{!contact.accountId}"/>
            <apex:outputField value="{!contact.phone}"/>
        </apex:pageBlockSection>
        </apex:pageBlock>
        </apex:form>
        </apex:page>
        NOTE:
        • Inline editing in Visualforce was introduced with the Spring'11.
        • Enabling inline editing is simple.
        • above example is related with the Contact Standard object.
        • this feature will work with custom objects also.

        Save an attachment in APEX

        Example for save an attachment in APEX.
        APEX CODE:
        public class status{
        private final Applicant__c applicant;
        public Blob resume {get; set;}
        public String contentType {get; set;}
        public String fileName {get; set;}
        public status(ApexPages.StandardController stdController) {
        this.applicant=(Applicant__c)stdController.getRecord();
        }
        public PageReference saveApplication() {
          try{
                insert(applicant);                                      
           }catch(System.DMLException e){
              ApexPages.addMessages(e);
               return null;
        }
        if(resume!=null){
              Attachment attach=new Attachment();
              attach.Body=resume;
              attach.Name=filename;
              attach.ContentType=contentType;
              attach.ParentID=applicant.id;
            try {
                  insert(attach);
              } catch(System.DMLException e) {
                  ApexPages.addMessages(e);
                  return null;
              }
          }
          PageReference p = Page.Confirmpage;
                p.setRedirect(true);
                return p;                   
        }
        }
        VISUALFORCE PAGE:
         <apex:page standardController="Applicant__c" extensions="status">
        <apex:form >
        <table>
        <tr>
        <td>Applicant Name </td>
        <td><apex:inputField value="{!Applicant__c.Name__c}"/></td>
        </tr>
        <tr>
        <td>CV </td>
        <td> <apex:inputFile accept="doc, txt, pdf" filename="{!fileName}" contentType="{!contentType}" filesize="1000" size="50" value="{!resume}"/> </td>
        </tr>
        <tr>
        <td></td>
        <td><apex:commandButton id="submitApplicant" value="Submit" action="{!saveApplication}"/></td>
        </tr>
        </table>
        </apex:form>
        </apex:page>

        Multi-Currency in Salesforce.com

        • Basically the multi-currency feature is not available in your organization on salesforce. We have to log a case or contact salesforce support team for activate the multi-currency feature on your organization.
        • This request can only be made by a System Administrator
        • Prior to converting your organization to multi-currency, some aspects of this feature that should be reviewed.
        • The Multi-Currency functionality CANNOT be turned off once it is activated. Salesforce.com support team also recommends testing the activation in a Sandbox environment.
        • The process locks the org when turning on Multi Currency (preventing users from logging in), this can take 30 minutes or more depending on the size of the organization.
        • After activate this feature on your organization, you will have a standard field called "CurrencyIsoCode" as picklist in ont only standard objects but also in custom objects
        • And You will have a place to manage your currencies in following path;
        Your Name-->Setup-->Administration Setup-->Company Profile-->Manage Currencies


        • In there, you can define all the currencies used by your organization.
        • Corporate Currency should be set to the currency in which your corporate headquarters reports revenue. If you designate a different currency as corporate, all conversion rates will be modified to reflect the change.
        • Any currency type created by you, CANNOT be deleted but can be deactivated.

        Friday, March 9, 2012

        Using Field Set on Visual Force Page

        This is about how we can use Field Set. We can dynamically bind fields on our visual force page using Field Set. It is very useful when we are working with managed package.

        A field set is a grouping of fields. For example we can have a field set that contains fields "Name , Email , Phone , Mobile". If the page is added to a managed package, administrator can add, remove, or reorder fields in a field set to modify the fields presented on visual force page without modifying any code. Creating a field set : Go to Setup > App Setup > Create > Objects > Select your object > Field Set (Beta) > New : 



        Fields in "In the Field Set" section is displayed on visual force page and administrator can add more fields in "In the Field Set" from "Available for the Field Set" section.

        Visual Force Page Code :

        <apex:page id="pageId" standardcontroller="My_Object__c">  
        <apex:form id="formId">  
            <apex:pageblock id="pbId">  
                <apex:pageblocksection columns="1" id="pbsIs">  
                    <apex:repeat value="{!$ObjectType.My_Object__c.FieldSets.MyFieldSet}" var="f">  
                        <apex:inputfield value="{!My_Object__c[f]}">  
                    </apex:inputfield></apex:repeat>  
                </apex:pageblocksection>  
            </apex:pageblock>  
        </apex:form>  
        </apex:page>  
        Now it will show three fields (Name, Email, Mobile) on visual force page, if we add "Phone" field from "Available for the Field Set" section to "In the Field Set" section then four fields (Name, Email, Mobile, Phone) will be displayed on visual force without changing the code.

        "IN" query Behaviour With SOSL

        Find something interesting and would like to share with you all.

        I was firing SOSL query in my organisation to get an account (using it as keyword search) :

        List<List<SObject>> lst = [Find 'test*' IN ALL FIELDS Returning Account] ;

        There are more than 1000 records of account in my organisation, as SOSL query result limit I was returned with 200 records only. Record which I was expecting is not here in those 200 records. So I put a condition in INQUERY returning account :

        List<List<SObject>> lst = [Find 'test*' IN ALL FIELDS Returning Account(id where id = '001A000000K1QS4')] ;

        Now I was expecting the record to be returned as I put the Id in the INQUERY but still the record is not returned. Actual behaviour is first SOSL get its first 200 records then the INQUERY Id is searched from those 200 records.

        Header Footer in PDF

        It is about how we can put header and footer in a visual force page which is rendered as PDF.

        <head>

        <style>

        @page {
            margin : 70pt .5in .5in .5in;
            @top-center {
                content : "My Header";
             }
            @bottom-left {
                content : "My Footer on Left Side";
                font-size : 10 px;
                color : #808080;
            }
            @bottom-center {
                content : "My Footer in center" ;
                font-size : 10 px;
                color : #808080;
            }
        }

        </style>

        </head>

        Now if we want to add a image in header then add:

        @top-center {
                content : element(header);
             }

        div.header {
            position : running(header) ;
        }

        in style and

        <div class="header">
            <apex:image value="Image URL" />
        </div>

        before the body. We can also change font-size , font family , color etc of page using @page style.

        How Salesforce 18 Digit Id Is Calculated

        As we know that each record Id represents a unique record within an organisation. There are two versions of every record Id in salesforce :
        • 15 digit case-sensitive version which is referenced in the UI
        • 18 digit case-insensitive version which is referenced through the API
        The last 3 digits of the 18 digit ID are a checksum of the capitalizations of the first 15 characters, this ID length was created as a workaround to legacy systems which were not compatible with case-sensitive IDs.
        The API will accept the 15 digit ID as input but will always return the 18 digit ID.

        Now how we can calculate the 18 Digit Id from 15 Digit Id :

        //Our 15 Digit Id
        String id = '00570000001ZwTi' ;

        string suffix = '';
        integer flags;
        for (integer i = 0; i < 3; i++) {
                  flags = 0;
                  for (integer j = 0; j < 5; j++) {
                       string c = id.substring(i * 5 + j,i * 5 + j + 1);
                       //Only add to flags if c is an uppercase letter:
                       if (c.toUpperCase().equals(c) && c >= 'A' && c <= 'Z') {
                            flags = flags + (1 << j);
                       }
                  }
                  if (flags <= 25) {
                       suffix = suffix + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
                  }else{
                       suffix = suffix + '012345'.substring(flags-25,flags-24);
                  }
             }

        //18 Digit Id with checksum
        System.debug(' ::::::: ' + id + suffix) ;

        System Debug

        Its very hectic to debug when we have too many script statements. Most of the time when we apply System.debug in our code with many script statement we get :

        *********** MAXIMUM DEBUG LOG SIZE REACHED ***********

        I get frustrated with this and started rolling over the pdf which says there is a solution for this. Now if I want to see a specific line debug which is coming almost in the end of our code so I will simply write this where I want to get the debug in my code :
        System.debug(Logginglevel.ERROR , ' ::::::: My Debug :::::::::::::') ;  
        And after this some steps to be done
        1. Create Debug logs from "Monitoring"
        2. Create Filters :
          • Database : NONE
          • Workflow : NONE
          • Validation : NONE
          • Callouts : NONE
          • Apex Code : ERROR
          • Apex Profiling : NONE
          • Visualforce : NONE
        So when I execute my code only debug with Logginglevel.ERROR will be displayed.

        Validation Over Apex

        Explaining a small example why we should use validations over apex. The key benefit is we don't have to write test class for it. Also if salesforce provide powerful tools like validations and workflows then why write APEX.

        I was jumping here and there in my code to find places where I can re-factor it to reduce code lines, what I got is this.

        public boolean validatePhone(account acc) 

         if (acc.Phone != null) 
         { 
          String phoneNumber = acc.Phone ; 
          Pattern phonePattern = Pattern.compile('\\D*?(\\d\\D*?){10}'); 
                Pattern numericPattern = Pattern.compile('[0-9]{10}'); 
                Matcher phoneMatcher = phonePattern.matcher(phoneNumber); 
                     
          if(phoneNumber.length() == 10) 
          { 
           Matcher numericMatcher = numericPattern.matcher(phoneNumber); 
           if(numericMatcher.matches()) 
           { 
            return true; 
           } 
           else 
           { 
            return false; 
           } 
          } 
          else 
          { 
           return false ; 
          } 
         } 
        }

        A apex code which validates a phone number, I am posting with some alterations as removing some unwanted code so please don't blame me if this code doesn't work after copy and paste.

        Why I have written this code? Because if any user entering value in phone field then I want them to enter value in particular format i.e. (XXX)XXX-XXXX and it should be of 10 digit.

        Then I just gave a thought over using validations and came up with a solution, writing a validation on account :
        IF( ISBLANK(Phone) , false , NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}")) ) 
        Now I don't need to write any code and any test class for it. I know there are some flaws in it but what my point is how we can reduce the apex code. Now don't just give a devil smile and start looking for the flaws.

        Salesforce Certification 401

        Here are some key points to be taken care of, which may help you to crack the bone of 401.For that you should have firm knowledge about :
        1. Sharing Rules / Org-Wide Default
        2. Approval Processes (Unanimous / Parallel / Skipping Steps / Dynamic Routing)
        3. Junction Object
        4. Master-Detail / Lookup / Hierarchical relationships
        5. Report / Report Types / Dashboards
        6. Data Loader / Import Wizard
        7. Formula Fields
        8. Analytical Snapshot
        9. Workflows
        10. Encrypted Fields / External Ids
        11. Governor Limits

        Encrypted Fields

        How to maintain sensitive data in salesforce?
        Answer is using Encrypted Fields.

        Encrypted Custom Fields are a new field type (released after winter 08) that allows users to store sensitive data in encrypted form and apply a mask when the data is displayed (e.g., Credit Card Number: XXX-XXX-XX-1234)

        Now how I can use encrypted fields in my organisation?
        You need get Encrypted Field Enabled from salesforce.com. Once you get it enabled from salesforce, you will see a new data type option when creating a new custom field.




        We can also specify the mask for the field.




        Some important points :

        1. User profiles who have the "View Encrypted Data" configuration enabled will be able to view the field normally.
        2. Users who do not have the "View Encrypted Data" profile will see the mask.
        3. User profiles that have the "Modify All Data" permission will not be able to see the value of encrypted data fields.
        4. The field length is restricted to 175 characters in size.
        5. Encrypted Field cannot be type cast as Unique or External ID.
        6. An encrypted field cannot be configured with a default value.
        7. You can't use encrypted fields in report filters and list views.
        8. You can't use the encrypted fields in SOQL "where/order" clauses.
        9. Also we can not use encrypted field formula fields, workflow rules, workflow field updates, approval process entry criteria, and approval step criteria.
        10. If you clone a record that has encrypted custom fields, Salesforce will copy the data from the field ONLY if the user has the "view encrypted data" permission.
        11. You can access the data of encrypted field in apex, i.e value is always unmasked.

        *Search the Salesforce.com Help & Training section, searching for "Encrypted Custom Fields" for more details.

        Calculating Age From Birth Date

        Answer for Calculating Age From Birth Date :
        Formula Code:
        IF(MONTH(TODAY())>MONTH(DOB_API),YEAR(TODAY())-YEAR(DOB_API),IF(AND(MONTH(TODAY())=MONTH(DOB_API),DAY(TODAY())>=DAY(DOB_API)),YEAR(TODAY())-YEAR(DOB_API),(YEAR(TODAY())-YEAR(DOB_API))-1)) 
        First simply if the month of present year is greater than date of birth than age will be calculated as the difference between present year and year of birth.

        Secondly if the first scenario fails two options comes in my mind, if the month of present year is same then is day of birth is same or not so if day of birth is greater than or equals to day of birth than age is calculated as we have done in the first scenario.

        Thirdly if above both scenarios fails that means month of present year and month of birth date is same but day of birth is smaller than day of present day. So age is calculated as the difference between present year and year of birth -1

        Using REGEX in Validations

        Example 1 : Validate Credit Card Number
        Description :

        Validates that a custom text field called Credit_Card_Number is formatted in 9999-9999-9999-9999 or 9999999999999999 number format when it is not blank.The pattern specifies:
        • Four digits (0-9) followed by a dash: \\d{4}-
        • The aforementioned pattern is repeated three times by wrapping it in () {3}
        • Four digits (0-9)
        • The OR character (|) allows an alternative pattern of 16 digits of zero through nine with no dashes: \\d{16}
        Validation Formula :
        NOT( REGEX( Credit_Card_Number__c ,  "(((\\d{4}-){3}\\d{4})|\\d{16})?"))  
        Error Message : Credit Card Number must be in this format: 9999-9999-9999-9999 or 9999999999999999.


        Example 2 : Valid IP Address
        Description :
        Ensures that a custom field called IP Address is in the correct format, four 3-digit numbers (0-255) separated  by periods.

        Validation Formula :

        NOT( 
        REGEX( IP_Address__c, 
        "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" 
        )) 
        Error Message : IP Address must be in form 999.999.999.999 where each part is between 0 and 255.


        Example 3 : US Phone Number Has Ten Digits
        Description :
        Validates that the Phone number is in (999) 999-9999 format. This works by using the

        REGEX function to check that the number has ten digits in the (999) 999-9999 format.


        Validation Formula : 
        NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}"))  
        Error Message : US phone numbers should be in this format: (999) 999-9999.


        Example 4 : Social Security Number Format
        Description :
        Validates that a custom text field called SSN is formatted in 999-99-9999 number format

        (if it is not blank). The pattern specifies:
        • Three single digits (0-9):\\d{3}
        • A dash
        • Two single digits (0-9):\\d{2}
        • A dash
        • Four single digits (0-9):\\d{4}


        Validation Formula :
        NOT( 
        OR( 
        LEN (Social_Security_Number__c) = 0, 
        REGEX( Social_Security_Number__c , "[0-9]{3}-[0-9]{2}-[0-9]{4}") 
        ))
         

         Error Message : SSN must be in this format: 999-99-9999.

        Inserting sObject Dynamically in Salesforce

        How I can insert sObject record dynamically?
        Visualforce Page code :
        <apex:page controller="InsertDynamicSobjectController">
            <apex:form >
                <apex:pageBlock >
                    <apex:pageBlockButtons >
                        <apex:commandButton value="Save" action="{!Save}"/>
                    </apex:pageBlockButtons>
                    <apex:pageMessages />
                    <apex:pageBlockSection >
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Enter Object Name"/>
                            <apex:inputText value="{!ObjectName}"/>
                        </apex:pageBlockSectionItem>
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Enter Name for Record"/>
                            <apex:inputText value="{!RecordName}"/>
                        </apex:pageBlockSectionItem>
                    </apex:pageBlockSection>
                </apex:pageBlock>
            </apex:form>
        </apex:page>
        Apex Code :
        public class InsertDynamicSobjectController
        {
            public String ObjectName {get; set;}
           
            public String RecordName {get; set;}
           
            public InsertDynamicSobjectController()
            {
                ObjectName = '' ;
                RecordName = '' ;
            }
           
            public PageReference Save()
            {
                //use GlobalDecribe to get a list of all available Objects
                Map<string, schema.sobjecttype=""> gd = Schema.getGlobalDescribe();
                Set<string> objectKeys = gd.keySet();
                if(objectKeys.contains(Objectname.toLowerCase()))
                {
                    try
                    {
                        //Creating a new sObject
                        sObject sObj = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
                        sObj.put('name' , RecordName) ;
                        insert sObj ;
                       
                        PageReference pg = new PageReference('/'+sObj.Id) ;
                        return pg ;
                    }
                    Catch(Exception e)
                    {
                        ApexPages.addMessages(e) ;
                        return null ;
                    }
                }
                else
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Object API name is invalid')) ;
                    return null ;
                }
            }
        }
        </string></string,>

        Fetching sObject Type From Record Id

        "How I can get the sObject Type from Record Id?". In many requirements I do have 15-digit or 18-digit Id and I want to know the sObject to which the Id belongs to. Answer is using Global Describe we can get the sObject type.

        Am getting too many emails from folks from Community Forums regarding this, so here is the generic method which will help all.
        public class KeyPrefix
        {
            // map to hold global describe data
            private static Map<String,Schema.SObjectType> gd;
           
            // map to store objects and their prefixes
            private static Map<String, String> keyPrefixMap;
            // to hold set of all sObject prefixes
            private static Set<String> keyPrefixSet;
           
            private static void init() {
                // get all objects from the org
                gd = Schema.getGlobalDescribe();
               
                // to store objects and their prefixes
                keyPrefixMap = new Map<String, String>{};
               
                //get the object prefix in IDs
                keyPrefixSet = gd.keySet();
               
                // fill up the prefixes map
                for(String sObj : keyPrefixSet)
                {
                    Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
                    String tempName = r.getName();
                    String tempPrefix = r.getKeyPrefix();
                    keyPrefixMap.put(tempPrefix, tempName);
                }
            }
           
            public static String GetKeyPrefix(String ObjId)
            {
                init() ;
                String tPrefix = ObjId;
                tPrefix = tPrefix.subString(0,3);
               
                //get the object type now
                String objectType = keyPrefixMap.get(tPrefix);
                return objectType;
            }
        }
        Now how you can use this? Simply save the class and pass your object Id in method "GetKeyPrefix" like this 
        //a0090000002QGKu will be your object Id
        System.debug('::::::: '+ KeyPrefix.GetKeyPrefix('a0090000002QGKu') );

        Displaying Role Hierarchy on Visualforce Page - Tree View

        Integrating Google Maps in Salesforce

        Just create a new visualforce page with this code
        <apex:page standardController="Account">
        <script src="http://maps.google.com/maps?file=api">
        </script>
        <script type="text/javascript">
        var map = null;
        var geocoder = null;
        var address = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";
        function initialize() {
        if(GBrowserIsCompatible())
        {
          map = new GMap2(document.getElementById("MyMap"));
          map.addControl(new GMapTypeControl());
          map.addControl(new GLargeMapControl3D());
         
          geocoder = new GClientGeocoder();
          geocoder.getLatLng(
            address,
            function(point) {
              if (!point) {
                document.getElementById("MyMap").innerHTML = address + " not found";
              } else {
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                marker.bindInfoWindowHtml("Account Name : <b><i> {!Account.Name} </i></b>
         Address : "+address);
              }
            }
          );
        }
        }
        </script>



        <div id="MyMap" style="width:100%;height:300px"></div>
        <script>
            initialize() ;
        </script>
        </apex:page>
        As you can see that I have used standard controller so you need to pass the account Id in URL. Let's say if the page name is "GoogleMaps" then the URL will look something like this : ".../apex/GoogleMaps?id=YOUR_ACCOUNT_ID".





        When you click on the balloon it will show you the Account name and the address, you can change it according to your need by changing the code of line "marker.bindInfoWindowHtml"


        Use this page as in line visualforce page on native layout and enjoy the Google maps with Salesforce.


        References
        http://code.google.com/apis/maps/documentation/webservices/
        http://code.google.com/apis/maps/index.html

        Difference between LookUp relationship and Master - Detail relationship in SFDC

        Lookup relationship is an example of loosely coupled relationship whereas Master-Detail is an example of Tightly coupled relationship.
        • In tightly coupled (M-D relation) when we delete the parent record, all child records are also deleted but nothing of this sort happens in loosely coupled (Lookup relation). Sure shot ADM 201,CON 201, DEV 401 question.
        • In M-D relation, a person who can view the master can see all the detail records of that master as the their is no owner on the detail side records and detail side gets its access properties from the master. Nothing of this sort happens in the Lookup relation as both objects have owners.
        • Roll up summary field can be made on Master Detail relation but not on the Lookup relationship.
        • One detail side record can have maximum 2 masters but no limit on the Lookup fields. DEV 401 certification question.
        • Standard objects can never be on the detail side of the master detail relationship but no such thing in a Lookup relation. (ADM 201)