Friday, September 11, 2015

JSforce that you can easily run the SalesforceAPI from JavaScript

JSforce that can run easily the SalesforceAPI from JavaScript. It is very convenient to try using Visualforce page of Developer environment.

Download the jsforce jibrary and create in static resource with name jsforce
https://cdnjs.cloudflare.com/ajax/libs/jsforce/1.5.0/jsforce.js


<apex:page>
    <apex:includeScript value="{!$Resource.jsforce}" />
    <apex:form>
        <apex:commandButton value="Get Count" onclick="return doClick();" />
    </apex:form>
    <script>
        var conn = new jsforce.Connection({accessToken: '{!$Api.Session_Id}'});
        function doClick () {
            var soqlQuery = 'SELECT Id, Name FROM Account';
            conn.query (soqlQuery, function (err, res) {
                if (err) {
                    alert (err);
                }
                alert (res.records.length);
            });
            return false;
        }
    </script>
</apex:page>

Wednesday, September 9, 2015

IP Address Geolocation

If you would like to know your ip address location based on the user ip address. here is best option you can go with.

I have created a visualforce page and an apex controller that makes a callout to external application with the user logged in ip address and will get back the response and displays in vf page. 

Add the endpoint url to Remote Site Settings 
http://www.telize.com

Vf page:
<apex:page controller="FindIpAddress" action="{!getipaddress}">
Country:{!country}<br/>
Isp:{!isp}<br/>
IP:{!ip}<br/>
Latitude:{!latitude}<br/>
Longitude{!longitude}<br/>
TimeZone: {!timezone}<br/>
</apex:page>


Apex Class
public class FindIpAddress {
    public String country {get;set;}
    public String isp {get;set;}
    public String ip {get;set;}
    public integer latitude {get;set;}
    public integer longitude {get;set;}
    public String timezone {get;set;}
 
 public void getipaddress() {
  string ReturnValue = '';  
  ReturnValue = ApexPages.currentPage().getHeaders().get('True-Client-IP');
  if (ReturnValue == '' || ReturnValue == null) {
   ReturnValue = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
  } 
  if (ReturnValue == '' || ReturnValue == null) {
   ReturnValue = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
  } 
  Http h = new Http();
  HttpRequest req = new HttpRequest();
  req.setEndpoint('http://www.telize.com/geoip/'+ReturnValue);
  req.setMethod('GET');
  HttpResponse res;
  try{
   res = h.send(req);
   Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(res.getbody());
   country =(String)m.get('country');
   isp=(String)m.get('isp');
   ip=(String)m.get('ip');
   latitude=(Integer)m.get('latitude');
   longitude =(Integer)m.get('longitude');
   timezone =(String)m.get('timezone');
  }catch(Exception e){
  }
 }
}

Uniqueness in combination of two fields

In the account object Say we have to maintain uniqueness on 2 fields(name and phone).

we need to create a new Text field that has been set as unique.  This field can then be updated based on a workflow rule.


Create a workflow
In the Rule Criteria section in the first drop down menu choose "Account: phone" not equal to and then leave the value blank. Click the “Save & Next” button.


click the "Add Workflow Action" drop down and click "New Field Update". Give the name to update the field name. In the Field to update dropdown choose the Field created. In the "Specify New Field Value" section choose "Use a formula to set new value". Click the “Show Formula Editor” link. Click "Insert Field". Find the "External Field" field. Click the "Insert" button. Click the "Save" button. Click the "Done" button. Click the "Activate" button.



This Can be achieved even with trigger. Please find the below code

trigger updateaccountExternalField on Account (before insert, before update) {

    Map<String, Account> accountMap =new Map<String, Account>();
    for (Account acc : Trigger.new){
        if ((acc.phone  !=null) &&(Trigger.isInsert ||(acc.phone  != Trigger.oldMap.get(acc.Id).phone))){
            if (accountMap.containsKey(acc.Name+acc.phone)){
                acc.External_Field__c .addError('Another Account has the same phone.');
            }else{
                accountMap.put(acc.Name+acc.phone, acc);
            }
       }
    acc.External_Field__c = acc.Name+acc.phone;
    }
    
    for (Account account : [SELECT External_Field__c FROM Account WHERE External_Field__c IN :accountMap.KeySet()]){
        Account newContact = accountMap.get(acc.External_Field__c);
        newContact.External_Field__c.addError('An Account with this phone already exists.');
    }
}