Sunday, August 12, 2012

Salesforce Deployment - Delete a file through ANT

I usually use the ant for deployment this is easy to use & also take less time then Eclipse deployment. Recently  I required to delete a resource from some salesforec org, & I found that there is no detail mentioned about this topic on internet. I keep digging this & come with the detail how you can delete a resource by ANT.
When we use ant deployment here is the folder hierarchy which we use-
ANT Sample Folder
                >>mypkg Folder
                >>retrieveUnpackaged Folder
                >> removecodepkg Folder [Create this new folder to delete the files]
                >>build.properties files
                >>build.xml

To delete a resource you need to add a destructiveChanges.xml  file in removecodepkg  folder. The destructiveChanges.xml file is same as package.xml. format of this file is as below-

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>LoginController</members>
        <members>LoginControllerTest</members>
        <name>ApexClass</name>
    </types>      
   <version>19.0</version>
</Package>

You also need to have a blank package.xml file in the same removecodepkg  folder. Format of the file will be-

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
  <version>19.0</version>
</Package>

Now you have two xml files in removecodepkg  folder –
1-destructiveChanges.xml  
 2-package.xml
  
ant is having build.xml file which have all commands can be executed. There will be a command to delete the code-

<target name="undeployCode">

      <sf:deploy username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" deployRoot="removecodepkg"/>
    </target>

  
Now mention the name of the resource in destructiveChanges.xml  file & delete the file from destination org. in our example I am deleting a class LoginController & it’s test class.
You just need to execute below command on ant
>>ant undeployCode
       


Partner Portal Login Page Customization & URL Masking for Partner Portal


Hope you are totally aware about the partner portal & site before going through this post. In the partner portal salesforce internally provide the default login page that is not user friendly. Here are some issues with the default portal login page-

#1-If you want to do some customization on the page like position, styles etc than it will a little bit difficult. Although you can use header & footer to add the custom style but there is some limitation if you want to fully customize this login box.

#2-Salesforce provide some default url for portal that is not user friendly. It will be something like as below
The url looks not good & not easy to remember if you want to spread to the portal users.

#3-Probably customer required branding at home page & in that case customize login page is a good option.

To avoid these issues you can create a custom login page & can also use site for URL masking (for any partner portal which in the same org). here is the steps 
by which you can do this-
#1-Hope you already having a partner portal in your org.

#2-Create a new site by registering a domain for that org.

let's say you rgister a site with below domain -
SitePortal so you site url will be http://SitePortal-developer-edition.ap1.force.com

#3-Create a dummy login VF page (Name - VFPortalLogin) for now, leave it blank, we will use this page in next step.

#4-Now go to Setup--> Site
create a site with some label. let's say you create MySite. So your site address will be
http://SitePortal-developer-edition.ap1.force.com/MySite
set the step #3 PortalLogin page as the default page
give the access to site as well as portal for this new page.

#5-Go to Setup--> Site --> Click on recently registered site --> click on Login Setting
Enable the Login (check the checkbox) for the partner which we created at first.

now open that page by site url, your url will be something like
http://SitePortal-developer-edition.ap1.force.com/MySite OR
http://SitePortal-developer-edition.ap1.force.com/MySite/PartnerLogin

you will see that blank login page which we created in previous steps. Upto this step notice that we are using the url masking for the portal. now we are going to start in the code part. here is the login VF page code, copy this code & paste in your VF page



<apex:page sidebar="false" showHeader="false" controller="PortalLoginController">
<apex:form forceSSL="true">
   <apex:styleSheet value="{!URLFOR($Resource.PortalResource,'/PortalCSS/elements.css')}" />
   <apex:styleSheet value="{!URLFOR($Resource.PortalResource,'/PortalCSS/common.css')}" />
   <apex:styleSheet value="{!URLFOR($Resource.PortalResource,'/PortalCSS/extended.css')}" />
   <apex:styleSheet value="{!URLFOR($Resource.PortalResource,'/PortalCSS/portal.css')}" />
   
    <style type="text/css">
        .username, .pw {
            width: 175px;
        }
    </style>
    <apex:pageMessages id="msg" />
       <div style="margin-top:60px;">
              <div class="portalheaderPRM">
                     <div style="width: 400px; margin: 0px auto; text-align: center; padding-right: 66px; padding-bottom: 10px; padding-top: 10px; margin-bottom: 10px;">
                            Put your LOGO here
                           
                     </div>
              </div>
       </div>
<div style="margin: 0px auto; width: 400px;">
       <table id="loginBox" class="bPageBlock" border="0" cellpadding="0" cellspacing="0" width="85%">
           <tr valign="top">
               <td>
                     <input type="hidden" name="startURL" value="" />
                       <div class="pbHeader">
                           <table border="0" cellpadding="0" cellspacing="0">
                               <tr>
                                   <td>
                                      
                                   </td>
                               </tr>
                               <tr>
                                   <td class="pbTitle">
                                       <h2>Secure Customer Login
                                       </h2>
                                   </td>
                               </tr>
                           </table>
                       </div>
                       <div class="pbBody">
                           <table border="0" cellpadding="0" cellspacing="0">
                               <tr>
                                   <td class="portalLoginLabel"><label for="username">User Name:</label></td>
                                   <td>
                                         <apex:inputText value="{!UserId}"  Styleclass="username" />

                                   </td>
                               </tr>
                               <tr>
                                   <td class="portalLoginLabel"><label for="password">Password:
                                   </label></td>
                                   <td>
                                         <apex:inputSecret value="{!UserPassword}"  Styleclass="pw" />
                                   </td>
                               </tr>
                           </table>
                           <div><a id="forgotPassword" href="/XXX_PortalPrefix/apex/PortalForgotPasswordVF">Forgot your password?
                                                </a>
                           </div>
                       </div>
                       <div class="pbBottomButtons">
                           <table border="0" cellpadding="0" cellspacing="0">
                               <tr>
                                   <td class="pbTitle"><img width="1" height="1" title="" class="minWidth" alt="" src="/s.gif" /></td>
                                   <td class="pbButtonb">
                                         <apex:commandButton value="Login" action="{!login}" />
                                   </td>
                               </tr>
                           </table>
                       </div>
             
               </td>
                     <td>
               <div class="pbFooter secondaryPalette"><div class="bg"></div></div>
               </td>
           </tr>
       </table>
</div>

</apex:form>
</apex:page>



you see that there are some resource used in the page. you can download these resource from the partner portal default login page>> view source. save all four CSS in a folder & upload it in static resource. set the path in the VF page as per your folder hierarchy.

now here is the controller code for that login page -


public class PortalLoginController {
      
       public String UserId {get;set;}
       public String UserPassword {get;set;}

       public PortalLoginController(){

       }
       public PageReference login(){
              PageReference pr =  Site.login(UserId, UserPassword,  '/apex/PortalHomepage');
              return pr;
       }
      
     
}



Create a new VF page & set it's name in controller so user will be redirect on that home page after logged in.

It's done, now you see that you can use a custom url for you portal, means we have done url masking.
whenever you need to add a new page you just need to add it at portal & you can use that with the same masked url..!! 


Wednesday, May 30, 2012

JS Remoting in Salesforce with Mustache



Js remoting is very useful & interesting feature. By this the page is not posted back to server & you will get result in less than a second...!!!

let's start with an example how this works. I am also going to use Mustache.js template in the VF page. Mustache is a js templates & can be used if you want to generate the html dynamically. It means you will define the template first & the data will be rendered as per the defined templates.

To know more about mustache you can check below url

to implement the js remoting first we need to create a controller class in apex.
Please notice that the apiVersion for controller class must be 23 or above.

global class JSremotingController {
     @RemoteAction
     global static OuterWrapper getOuterWrapperObject(string oppId){
         return null;
     }
   @RemoteAction
   global static OuterWrapper setOuterWrapperObject(String jsonString, string oppId){
      return null
   }

global class InnerWrapper{
   public string name {get;set;}
   public string description {get;set;}
   public InnerWrapper(String strName, String strDesceription){
      this.name = strName;
      this.description = strDesceription;
   }
}
global class OuterWrapper{
  public String oppName {get;set;}
  public String oppDescription {get;set;}
  public List<InnerWrapper> listOfInnerWrapper {get;set;}
  public List<String> listOfStr_SelectOptions {get;set;}
  public OuterWrapper(Opportunity o){
     listOfStr_SelectOptions = SelectOptions_Global;
     listOfInnerWrapper = new List<InnerWrapper>();
     oppName = o.Name;
     oppDescription = o.Description;
   }
  }
}


let's dig the code step by step-

@RemoteAction
global static OuterWrapper getOuterWrapperObject(string oppId){
}

this method is defined as remote action by @RemoteAction tag
it must be declared with global & static keyword because the function is related to class instance. It will be called by js remoting to get the data on VF page.


@RemoteAction
global static OuterWrapper setOuterWrapperObject(string oppId){
}

this method is same as above just the difference is we will use this to update the opportunity description.

There are two wrapper class. One is main class & other class list used in main class. The reason why I took this wrapper class structure to explain how we can deserialize the input (json string) directly to wrapper class.

Now again taking the implementataion part for the methods-



@RemoteAction
global static OuterWrapper getOuterWrapperObject(string oppId){
   Opportunity opp = [Select o.Name, o.Id, o.Description From     
   Opportunity o WHERE Id=:oppId];
    OuterWrapper objOuterWrapper = new OuterWrapper(Opp);
    List<InnerWrapper> WrapperT = new List<InnerWrapper>();
    listOfInnerWrapperT.add(new InnerWrapper('TEST1','DESC1'));
    objOuterWrapper.listOfInnerWrapper = listOfInnerWrapperT;
   return objOuterWrapper;
}





in this method we will pass a opp od from the VF page, the code will get the detail from the database create wrapper & return this.
In JS we will get a js object of OuterWrapper, we can directly access it's field same as we get the value we get in javascript code. You will get it more clearly as I will add the vf page in nect couple of lines.

@RemoteAction
global static OuterWrapper setOuterWrapperObject(String jsonString, string oppId){
   OuterWrapper objOuterWrapper =   
   (OuterWrapper)System.JSON.deserialize(jsonString,OuterWrapper.Class);
  Opportunity opp = new Opportunity(Id=oppId);
   opp.Description = objOuterWrapper.oppDescription;
  update opp;
  return objOuterWrapper;
}
this method simply updateting the opp description. This method will be called from the VF page buttton.

Now let's move on the VF page detail-

first of all you need to include the js files for this. There are two js files-

<apex:includescript value="{!URLFOR($Resource.JS,'jquery-1.4.2.min.js')}" />
<apex:includescript value="{!URLFOR($Resource.JS,'mustache.js')}" />

I have to include these files because I am using the mustache in the page, you can avoid this if not required.

function getOuterWrapperObjectByJSRemoting(oppId) {
  JSremotingController.getOuterWrapperObject(oppId, function(result, event){
  if (event.status) {
   result_Global= result;
   var template = "<b><span>Opportunity Name:</span>  {{oppName}}</b><br/><br/><span>Opportunity Description</span>  {{oppDescription}}";
   var html = Mustache.to_html(template, result);
   $('#SPANOppName').html(html);
  } else if (event.type === 'exception') {
    alert("exception");
    document.getElementById("responseErrors").innerHTML = event.message;
  } else {
   alert("else");
   document.getElementById("responseErrors").innerHTML = event.message;
  }
}, {escape:true});
}

by this js method we will pass a opp id & will get the detail in jsObject result. You can check/run result_Global on the console to check the structure of the js object.






function SetOuterWrapperObjectByJSRemoting(jsonString, oppId){
  JSremotingController.setOuterWrapperObject(jsonString, oppId, function(result, event){
  if (event.status) {
    result_Global2 = result;
    alert('updated..!!');
  } else if (event.type === 'exception') {
    alert("exception");
    document.getElementById("responseErrors").innerHTML = event.message;
  } else {
    alert("else");
    document.getElementById("responseErrors").innerHTML = event.message;
  }
 }, {escape:true});
}

this method simply udate the opp description by js remoting.

function getJSONObject(){
//Outer Wrapper
var objOpportunityWrapper = new Object();
objOpportunityWrapper["oppDescription"] = $("#inputOppDescription").val();
var InnerWrapper = new Object();
var InnerWrapperArray = new Array();
InnerWrapper["name"] = 'TEST Name1';
InnerWrapper["description"] = 'TEST Description1';
InnerWrapperArray[0] = InnerWrapper;
objOpportunityWrapper["listOfInnerWrapper"] = InnerWrapperArray;
JSON_STR = JSON.stringify(objOpportunityWrapper);
SetOuterWrapperObjectByJSRemoting(JSON_STR,Opp_Id);
}

I think this is the most important method on the js. this method is going to create structure same as the wrapper class. it there is any difference in between the object you created on JS & controller class than the json string will not be serialized in controller.


let's put the whole code in one place-

class code will be

global class JSremotingController {
  private static List<String> SelectOptions_Global =    
  getFieldDescibe(Opportunity.LeadSource.getDescribe());
  
public static List getFieldDescibe(Schema.DescribeFieldResult Res){
  List<String> listOfOpt = new List<String>();
  List<Schema.PicklistEntry> pe = Res.getPicklistValues();
  if(pe != NULL && pe.SIZE()>0){
    for(Schema.PicklistEntry p:pe){
       listOfOpt.add(p.getLabel());
    }
  }
  return listOfOpt;
}

@RemoteAction
global static OuterWrapper getOuterWrapperObject(string oppId){
  Opportunity opp = [Select o.Name, o.Id, o.Description From Opportunity o WHERE Id=:oppId];
  OuterWrapper objOuterWrapper = new OuterWrapper(Opp);
  List<InnerWrapper> listOfInnerWrapperT = new List<InnerWrapper>();
  listOfInnerWrapperT.add(new InnerWrapper('TEST1','DESC1'));
  objOuterWrapper.listOfInnerWrapper = listOfInnerWrapperT;
  return objOuterWrapper;

}
@RemoteAction
global static OuterWrapper setOuterWrapperObject(String jsonString, string oppId){
  OuterWrapper objOuterWrapper =  
  (OuterWrapper)System.JSON.deserialize(jsonString,OuterWrapper.Class);
  Opportunity opp = new Opportunity(Id=oppId);
  opp.Description = objOuterWrapper.oppDescription;
  update opp;
  return objOuterWrapper;
}
global class InnerWrapper{
  public string name {get;set;}
  public string description {get;set;}

  public InnerWrapper(String strName, String strDesceription){
    this.name = strName;
    this.description = strDesceription;
 }
}
global class OuterWrapper{
  public String oppName {get;set;}
  public String oppDescription {get;set;}
  public List<InnerWrapper> listOfInnerWrapper {get;set;}
  public List<String> listOfStr_SelectOptions {get;set;}
  public OuterWrapper(Opportunity o){
    listOfStr_SelectOptions = SelectOptions_Global;
    listOfInnerWrapper = new List<InnerWrapper>();
    oppName = o.Name;
    oppDescription = o.Description;
  }
}
}

VF Page

<apex:page controller="JSremotingController" sidebar="false" showHeader="false">
 <apex:form id="form1">
 <apex:includescript value="{!URLFOR($Resource.JS,'jquery-1.4.2.min.js')}" />
 <apex:includescript value="{!URLFOR($Resource.JS,'mustache.js')}" />
 <script type="text/javascript">
   var result_Global;
   var Opp_Id = '006900000071POn';
   function getOuterWrapperObjectByJSRemoting(oppId) {
  JSremotingController.getOuterWrapperObject(oppId, function(result, event){
  if (event.status) {
      result_Global= result;
var template = "<b><span>Opportunity Name:</span>  {{oppName}}</b><br/><br/><span>Opportunity Description</span>  {{oppDescription}}";
       var html = Mustache.to_html(template, result);
       $('#SPANOppName').html(html);
                      
   } else if (event.type === 'exception') { 
       alert("exception");
       document.getElementById("responseErrors").innerHTML = event.message;
   } else {
       alert("else");
       document.getElementById("responseErrors").innerHTML = event.message;
   }
}, {escape:true});
 }

$(document).ready(function(){
   getOuterWrapperObjectByJSRemoting(Opp_Id);
});
var result_Global2;
 function SetOuterWrapperObjectByJSRemoting(jsonString, oppId){
  JSremotingController.setOuterWrapperObject(jsonString, oppId, function(result, event){
  if(event.status) {
    result_Global2 = result;
       alert('updated..!!');
  } else if (event.type === 'exception') {
       alert("exception");
       document.getElementById("responseErrors").innerHTML = event.message;
  } else {
       alert("else");
       document.getElementById("responseErrors").innerHTML = event.message;
  }
 }, {escape:true});
}
var JSON_STR;
function getJSONObject(){
  //Outer Wrapper
  var objOpportunityWrapper = new Object();
  objOpportunityWrapper["oppDescription"] = $("#inputOppDescription").val();
                    
  var InnerWrapper = new Object();
  var InnerWrapperArray = new Array();
  InnerWrapper["name"] = 'TEST Name1';
  InnerWrapper["description"] = 'TEST Description1';
  InnerWrapperArray[0] = InnerWrapper;
  objOpportunityWrapper["listOfInnerWrapper"] = InnerWrapperArray;
  JSON_STR = JSON.stringify(objOpportunityWrapper);
  SetOuterWrapperObjectByJSRemoting(JSON_STR,Opp_Id);
}   
                    
</script>    
  <apex:pageBlock title="GET DATA BY JS REMOTING">
 <apex:pageBlockSection >
  <span id="SPANOppName"></span>
 </apex:pageBlockSection>
  </apex:pageBlock>  
  <apex:pageBlock title="SET/UPDATE DATA BY JS REMOTING">
<apex:pageBlockSection >
  <apex:pageBlockSectionItem >
  <span>Opportunity Description</span>
  <input type="text" id="inputOppDescription" />
  </apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<input type="button" onclick="getJSONObject()" value="Update" class="btn"/>
</apex:pageBlockSectionItem>
 </apex:pageBlockSection>
   </apex:pageBlock>
  </apex:form>  
</apex:page>

to run this example you just need to copy & paste & change the Opp id in in the top of the vf page.
 var Opp_Id = '006900000071POn';


the page ui will be as below