Monday, November 14, 2016

How can you update Salesforce record using Apex, when you don’t know Object API name, but you know record Id ?

Using Dynamic Apex we can achieve this :
1//Lets assume this is record Id
2Id recId = 'a0P9000000ESXcV';
3 
4Schema.SObjectType token = recId.getSObjectType();
5Sobject s = token.newSobject();
6s.put('Id',recId );
7s.put('Name', 'om');
8update s;

What is best practice to refer dynamic custom messages in Visualforce with multi-language support ?

Using Custom Label or OutputField or InputField tag, Platform itself will take care of internationalization. However in some cases, Message needs to be dynamic at the same time it should also support muti-language. In Custom Label, we cannot save dynamic String.
Let’s assume we want to show message something like “DEVELOPERNAME is not authorized to access this page”.
Here, Developername should be dynamically changed in visualforce which supports multilanguage. For each developername, it is not feasible to create custom labels. So below workaround can be used :
Step 1 : Create a Custom Label with text “{0} is not authorized to access this page“. In every language, dynamic value should represented by {0}.
Step 2 : In Controller of Visualforce write something like this :


1String developerName = 'Some DeveloperName';
2String message = String.format(Label.DEVELOPERNA, new String[] { developerName });

Which component in Salesforce ends with “__mdt” and “__s”?

Custom metadata types ends with “__mdt” (meta data type), just like custom object or custom fields ends with “__c”.
When we create Geolocation field in Salesforce, lets say by name “location__c” then internally Salesforce creates subfields with extension “__s“. In this case “location_latitude__s” and “location_longitude__s”.

What is custom metadata type ?

Custom metadata was introduced generally in Summer 15 release. Before Custom metadata type, we were using Custom settings of List type. Problem with custom setting was that, during migration or in packages, data were not migrated. We had to either use data loader or some API to create initial data. However, if we package custom metadata type or migrate it, data will also be migrated along with it.

How to report on User License field?

Create formula field in User Object with formula “Profile.UserLicense.Name”.
Note: You need to copy and paste this value because it doesn’t show up in the fields drop down.

Which custom fields or relationships in salesforce ends with “__pc” and “__pr” ?

In normal scenario all custom fields ends with “__c” and relationships ends with “__r” However for Person accounts, custom fields ends with “__pc” and custom relationship ends with “__pr”.

Capture errors after using Database DML methods in Salesforce.

List<Contact> lstContact = new List<Contact>();
Contact con = new Contact (lastName = 'Sharma', SQL_Server_Id__c='3',firstName='Abhinav');
lstContact.add(con);
//.. Other Contact records added in List
Database.UpsertResult[] results = Database.upsert( lstSGAccOppInsert, Contact.SQL_Server_Id__c.getDescribe().getSObjectField() ,false ) ;

for(Integer i=0;i<results.size();i++){
    if (!results.get(i).isSuccess()){
        Database.Error err = results.get(i).getErrors().get(0);
        System.debug('Error - '+err.getMessage() + '\nStatus Code : '+err.getStatusCode()+'\n Fields : '+err.getFields());
    }
}

Monday, November 7, 2016

SALESFORCE INTEGRATION WITH .NET USING SOAP API

Required : 
1. .Net end point (or) WSDL wile 
NOTE : If client provides WSDL file no need to follow STEP 1 
STEP 1 :

Copy the .Net Endpoint given by the client (https://xxxxxxxxxxxx/gw/xxxx/nextgencrm/ldap.getpicture.dev)
Go to the web browser open new tap paste it and add (?wsdl) 
EX: https://xxxxxxxxxxxx/gw/xxxx/nextgencrm/ldap.getpicture.dev?wsdl 
Copy the XML data and paste in notepad or notepad++
Remove one binding and related port in that XML because sales force support only one binding
EX: 
Remove second binding and related port
Binding:
-------
<wsdl:binding name="LdapSoap12" type="tns:LdapSoap">
.
.
.</wsdl:binding>
Port:
-----
<wsdl:port2 name="LdapSoap" binding="tns:LdapSoap">
<soap:address location="xxxxxxxxxxxx" />
</wsdl:port2>
Save the file as MyService.wsdl on your desktop 
STEP 2:
Login in to your sales force account
Go to setup > Build > Develop > Apex
Click on Generated Apex

Browser and select MyService.wsdl file and Parse it
If successfully parse Change the name of class as MyDotnetService and save it

STEP 3 :

Open the class MyDotnetService it look like below example 
EX: 
public class MyDotnetService {
public class HelloWorld_element {
private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
private String[] field_order_type_info = new String[]{};
}
public class HelloWorldResponse_element {
public String HelloWorldResult;
private String[] HelloWorldResult_type_info = new String[]{'HelloWorldResult','http://tempuri.org/',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
private String[] field_order_type_info = new String[]{'HelloWorldResult'};
}
public class LdapSoap {
public String endpoint_x = 'https://xxxxxxxxxxxxxxxxxxxxxx/gw/xxxxxxxxxx/nextgencrm/ldap.getpicture.dev';
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://tempuri.org/', 'MyDotnetService'};
public String HelloWorld() {
MyDotnetService.HelloWorld_element request_x = new MyDotnetService.HelloWorld_element();
MyDotnetService.HelloWorldResponse_element response_x;
Map<String, MyDotnetService.HelloWorldResponse_element> response_map_x = new Map<String, MyDotnetService.HelloWorldResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://tempuri.org/HelloWorld',
'http://tempuri.org/',
'HelloWorld',
'http://tempuri.org/',
'HelloWorldResponse',
'MyDotnetService.HelloWorldResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.HelloWorldResult;
}
}
} 
STEP 4 : 
Go > setup > Administer > Security Controls > Remote Site Settings > New Remote Site
Add Endpoint URL given by client
If client given WSDL file , Go to generated class ( MyDotnetService )

MyDotnetService > LdapSoap > endpoint_x

copy the end point and paste in remote site settings

STEP 5 :

Open the workbench or developer console

Copy class Name , sub class name , and method name like below example 
EX:

MyDotnetService.LdapSoap ldap = new MyDotnetService.LdapSoap();
String response = ldap.HelloWorld();
System.debug('response--------'+response); 
NOTE :

If time out error came, Add below code
ldap.TimeOut_x = 60000;

Now you successfully integrated sales force with .Net using SOAP API 
NOTE : This process is works only when client end point has no Authorization

DISPLAY ONE VISUAL FORCE PAGE DATA IN TO ANOTHER VISUAL FORCE PAGE

This can be done using attribute include.


 We have to just specify the name of the visual force page and include this attribute in our visual force page.

<apex:insert>
<apex:composition>
<apex:define>


EX:
VF 1:
----

                 VF page name Template.

                <apex:page >
<apex:outputText >Welcome to Accord</apex:outputText><br/><br/>
<apex:insert name="header"/><br/><br/>
<apex:outputtext >We are Pioneer in training students</apex:outputtext><br/><br/>
<apex:insert name="body"/><br/><br/>
<apex:outputtext >Thank You</apex:outputtext>
</apex:page>

VF 2:
----

<apex:page sideBar="false">
<apex:composition template="Template">
<apex:define name="header">
Accord welcomes you!
</apex:define>
</apex:composition>
</apex:page>

SALESFORCE TO SALESFORCE INTEGRATION USING REST/SOAP API

For sales force to sales force integration required  Two organization

1. Sales Force Org 1 
2. Sales Force Org 2

STEP 1 : Create one ViSsula Force Page and Controller in Sales Force Org 2


Visual Force Page: (Page Name : sfdc_to_sfdc)

<apex:page controller="ExternalServiceCall">
<apex:form >
<apex:commandButton value="CallService" action="{!callMethod}" title="CallService"/>
</apex:form>
</apex:page>

Apex Controller:

public class ExternalServiceCall {
public PageReference callMethod() {
String Endpoint = '';
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(Endpoint);
req.setMethod('POST');
HTTPResponse res = http.send(req);
System.debug('----------------'+res.getBody());
return null;
}
}

STEP 2 : Create one CONNECTED APP in Sales Force Org 1

1. Go to SETUP > BUILD > CREATE > APP > CONNECTED APP > NEW

Connected App Name : S_TO_S_APP

Contact Email : Your Email Address

API (Enable OAuth Settings) : Check (Enable OAuth Settings)

Callback URL : Sales Force Org 2 visual force page URL (sfdc_to_sfdc)

EX: https://c.ap2.visual.force.com/apex/CallExternalService

Selected OAuth Scopes : Select all and move from left to right


2. SAVE

STEP 3 : Copy consumer key and Consumer Secret and paste in note pad


1. Consumer Key (3MVG9Y6d_Btp4xp46JlONG7HS6J2U7.oBhNF2mAUQhyotYkFWexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)

2. For consumer secret click on reveal copy the code (86658178********)

STEP 4 :

https://**salesforce instance**/services/oauth2/authorize?response_type=code&client_id=**Cosumer key**&redirect_uri=**Callback URL**&state=mystate1

In Above URL replace below given parameters

1. **salesforce instance** : Replace with your sales force org instance

2. **Cosumer key** : Consumer Key of connected APP which we copied in the above step

3. **Callback URL** : Sales Force Org 2 visual force page URL

4. State : give your own string in state

Note : state should be different every time your calling this URL


STEP 5 : Copy the Above URL and open in a new browser

1. It will open an window which asking to permission (Allow IT)

2. It will ask your Sales Force Org 2 credentials (Give your credential and login)

3. Page Redirect to visual force page (sfdc_to_sfdc)

4. Visual force URL should look like 
https://c.ap2.visual.force.com/apex/CallExternalService&code=aPrxqJ8A8kLOza.1WWrtEdk2HbfhS3ZFa7OAR20zsgGyVdnZVO_ieN6nRxWBwka19lulk3RoTg%3D%3D&state=mystate1 

5. From the URL copy the CODE and paste in note pad

STEP 6 :

https://**salesforce instance**/services/oauth2/token?code=**code**&grant_type=authorization_code&client_id=**Consumer Key**&client_secret=**Consumer Secret**&redirect_uri=**Call Back URL**

Above URL is to get the Access Token

1. **salesforce instance** : Replace with your sales force org instance

2. **code** : STEP 5

3. **Consumer Key** : STEP 3

4. **Consumer Secret** : STEP 3

5. **Call Back URL** : Sales Force Org 2 visual force page URL

NOTE: Go to Remote site settings and create new remote site (Name : salesforceOrg, URL : **salesforce instance**)

STEP 7: Copy the above URL and paste in STEP 1 class > method > String  Endpoint


1. Class : ExternalServiceCall

Method : callMethod

String Endpoint = STEP 6 (URL)

2. Save

3. Click on Save button

4. Go to the debug log

5. Copy the Access Token

Now Integration is Done with sales force now you can make calls from sales force to sales force

   STEP 8: To call class of Sales Force Org 1 from Sales Force Org 2

EX:

Create a class in Sales Force Org 1

Apex Controller :

@RestResource(urlMapping='/sfdcCalling/*')
global class SalesforceOrg{
@HttpGet
global static List<Contact> sfdcMethod(){
List<Contact> sfdcContact = new List<Contact>();
sfdcContact = [select Name,Email from Contact];
return sfdcContact;
}
}

Call Above calss (SalesforceOrg) From Org 2

Copy the below code and paste in developer console or workbench in Sales Force Org 2 and executive

String accessToken = '00D90000000iCmb!AR4AQKhpsb2wJYLLxdafV71KdkRxBmRuRmWD_LTmEtRkFdxTWYh_V7CPqc*******************************';
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://immu-dev-dev-ed.my.salesforce.com/services/apexrest/sfdcCalling');
req.setMethod('GET');
req.setHeader('Authorization',' Bearer '+accessToken);
HTTPResponse res = http.send(req);
System.debug('----------------'+res.getBody());

Note : 
Access Token : From STEP 7

setEndpoint : should be Sales Force Org 1 Endpoint ,In above http call the end point is Sales Force Org 1 class Annotation Name(sfdcCalling)

STEP 9: For more endpoints please refer the below URL

https://developer.salesforce.com/page/Creating_REST_APIs_using_Apex_REST