Monday, 29 July 2019

Aggregate Result

Use Case : Contract is having multiple documents attached to the related list 'Notes & Attachment',Get the latest attachment document id for each contract.


The Below Code contains:
1.Set Value Assignment 
2.Map Creation
3.SOQL Group By & Having Clause
4.Aggregate Query 
5.Verifying the size of Aggregate Result/Map/Set values
6.Read the Aggregate Result
7.Add values to the Map  from aggregate result
8.Type Casting Aggregate Result
9.Return Type - Map
10.Reading the Map Value
Note : Aliasing the  SOQL field possible only in Aggregate result
       
public static Map GetContractLatestAttachment(Set ContractIds) //Set Value Assignment
    {
        Map ContractAttachMap = new Map(); //Map Creation
        //Get the latest attachment record ID
        //Aggregate Query 
        //SOQL Group By & Having Clause
        AggregateResult[] contrAttAggResults = [SELECT Max(Id) Id,ParentId  FROM Attachment 
                                                Group By ParentId Having ParentId in:ContractIds];     
        //Verifying the size of AggregateResult values 
        if(contrAttAggResults.size()>0)
        {
            //Read the Aggregate Result
            for(AggregateResult aggResult : contrAttAggResults)
            {
            // Add values to the Map from Aggregate Result  
            // Type Casting Aggregate Result - Id as per map declaration
              ContractAttachMap.put((Id)aggResult.get('ParentId'), (Id)aggResult.get('Id')); 
            }        
        }
        return ContractAttachMap;//Return Type - Map
    }         

       
 
       
public void UpdateContractWithLatestAttachmentId()
{
 Map ContractAttachMap = GetContractLatestAttachment();
 //Reading the Map Value
 if(ContractAttachMap != null)
 attachId = ContractAttachMap.get(conRecord.Id);
}

       
 

Sunday, 14 July 2019

S2S File Sharing

For Salesforce 2 Salesforce Introduction & FAQ Refer

1.PDF File sharing is possible in S2S ?
Yes,Using the ‘Attachment’ related list 

Publish & Subscribe the Attachment object from Org1 to Org2.
Note : To all the supported objects of S2S only.Refer

2.More than one pdf file can be shared ?
Yes,Whatever the part of Attachment object all files will be transferred.

3.Is there any limit on file size? What should be the size of file ?
Yes,It should be 20 MB  / Less [Each File size]

4.What happens if the file size is more than 20MB ?
There will not be any error / validation/no log in the connection history,The parent record will gets published and this attachment child record will be in queue forever.
Ex: Account & Attachment published - Account will get received but not the attachment because of its huge size.

5.In case of multiple files,Can we punch only the specific file to share?
Yes,
Solution 1 :  Using “Share with connections” checkbox on the attachment file detail.



Solution 2 :  While programmatically forwarding the record then can query the record based on the  business rule and send only that record. 

PartnerNetworkRecordConnection newConnection = new PartnerNetworkRecordConnection( ConnectionId = network.Id,
LocalRecordId = a.id,
ParentRecordId =a.id.ParentId, 

SendClosedTasks = false, SendOpenTasks = false,SendEmails = false);

6.Share the Contract PDF from one org to another?
Contract is not supported in S2S integration,Refer below link to know the unsupported standard objects.Refer
Workaround will be attach the contract pdf to any of the supported objects and tune the business logic to achive this requirement.

7.Programatically can share the attachment files ?
Yes

8.In S2S,How to share the files programatically ?
Solution 1 : While sharing the parent record programmatically add the below attribute to share the attachment child records.



------------------------------------------------------------------------------------------------------------------------
// Define Network id
String connectionName = 'SF_Bytes'

List<PartnerNetworkConnection> partnerNetConList =  [Select id from PartnerNetworkConnection where connectionStatus = 'Accepted' and connectionName = :connectionName];

Id networkId = partnerNetConList.get(0).Id;

// Send Parent & Child (Attachment File) programatically
PartnerNetworkRecordConnection newConnection = new PartnerNetworkRecordConnection( 
            ConnectionId = networkId, 
            LocalRecordId = '0010S00000OnyrK', SendClosedTasks = false, 
            SendOpenTasks = false, SendEmails = true,RelatedRecords='Attachment');

insert newConnection;
------------------------------------------------------------------------------------------------------------------------


Solution 2 : Write trigger logic on the Attachment and insert the record into the PartnerNetworkRecordConnection along with the Parent Record Id & Attachment Record Id.

9.Continuous sync of attachment files possible ? 
No,It will not publish the new attachment once the parent record is published.
will through an exception.


Solution : Re-publish the parent record by selecting the attachment file with “Share with connections” check box.
Ex1.: Account → Added one Attachment & Published the Account & Attachment ,Expected O/P both will get received in the target  org.
Later added another attachment to that Account ,That will not get published.
Ex2: Publish the parent record & Later add the attachment through programmatically.That will not get published.
Refer the above solution.

10.How to test the status of the published record Parent & Child? 


Thursday, 4 July 2019

Export Apex Result To CSV File

Use Case : Get the Contract object Field Label  and Field Name (API) name & Export that result to CSV file and Send Email Notification.


//To get all the objects details    
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get('Contract').getDescribe().fields.getMap();
string header = 'FIELD LABEL , FIELD NAME\n'; //CSV Header Row
string contrExcelStr = header ;

//Loop through the field map and get the object field label & field name(API Name)
for(Schema.SObjectField sfield : fieldMap.Values())
{
 schema.describefieldresult descField = sfield.getDescribe();
 mapResult.put(descField.getLabel(),descField.getname());
 string recordString = descField.getLabel() +','+descField.getname() +'\n';
 contrExcelStr = contrExcelStr +recordString;
}

 //Email Notification
Messaging.EmailFileAttachment contrCsvAttch = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(contrExcelStr);
string csvname= 'Contract.csv';
contrCsvAttch.setFileName(csvname);
contrCsvAttch.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'test@gmail.com'};
String subject ='Contract CSV';
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody('Contract CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{contrCsvAttch});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

//Sent Email 


Tuesday, 2 July 2019

Salesforce 2 Salesforce Connect

S2S File Sharing Refer

1.What is Salesforce 2 Salesforce Connect ?
It is point-and-click integration tool that allows you to replicate data between 2 orgs.
Ex: Create account in one org and that should share with another org

2. All standard & custom objects records can be shared?
No,You can publish only certain objects
  • Account
  • Attachment (unencrypted)
  • Case
  • Case Comment
  • Contact
  • Lead
  • Opportunity
  • Opportunity Product
  • Product
  • Task
  • Custom Object
3.Pros & Cons of S2S ?
Pros :
1.S2S allows you and your business partners to collaborate more easily and effectively.
2.You can share records with one or more connections.
Cons :
1.S2S can be between 2 sandboxes / 2 production org not between sandbox & production org.
2.You can’t accept forwarded records on the Salesforce mobile app.
3. You can not publish the look up Id's.
4. There is no upsert on the object 'PartnerNetworkRecordConnection',Only Insert can perform.

4.Explain with business use case ?
In real time,Consider a company acquired 2 different companies & Each has its own ERP system and then required to merge those systems,
Ex: Opportunity of one system should trigger to another system and the remaining business rules will trigger in other system.

5.Explain Steps for S2S implementation?
1.Enabling Salesforce to Salesforce (S2S),In both source & target org.
A new user named “Connection User” is created on the enable.
"Connection user"  - Is the user that performs the actions on behalf of the shared connection

2.S2S integration user in Source & Target Org


3.Create Contact & Account in Source & Target Org - Use the same email id of the contact in both the orgs.

4.Setup a connection,The connection tab will be available only after S2S enabled.


5.Send Invite to the contact on the new connection establishment request,The contact of the source & target will be pointed to same email id,Consider this as "Connection User" exist in both orgs.If invite is accepted then connection gets established.



6.Publish Objects

7.Subscribe Objects & Auto-Accept
If Auto-Accept is not selected then administrator has to review the incoming records and then accept,

8.Field Mapping & Pick List Field Value Mapping (Click on the Edit Values to map)


9.Share Record By Forward To Connection


10.The shared record system info details,The created by is "Connection user"

11.External Shared Related List,If not available add to the page layout.


6.Is it possible to automate S2S configuration / Field Mapping ?
No. There's no SOAP, REST, Tooling, or Metadata object that represents a field mapping for S2S,
Either through manual / Scripting (Selenium)/ Browser Control Technique (UI Path).
Refer

7.How to know the status of shared record ?
If we select option "Send Email",It will send an email with the details of shared record / In case of any error while sharing the record that details will be sent & Same will be available in the "Connection History" of the connection.




8.Expected errors & Solutions ?
1.Insufficient Privileges on click of connection establishment link
Sln:Enable S2S in this org
2.Forward To Connections button not found
Sln:
-->The 'Forward to Connections' button is only visible when the User viewing the object list view has the 'Manage Connections' permission enabled either via the Profile or via a Permission Set.

-->Add that button in the Search layout -->List View Layout


8.What are the PartnerNetworkConnection & PartnerNetworlRecordConnection?

PartnerNetworkConnection
PartnerNetworkRecordConnection
This object represents a Salesforce to
Salesforce connection
between Salesforce organizations.
This object represents a record shared
between Salesforce organizations using
Salesforce to Salesforce.
9.How to share the record programmatically in S2S apart from using the 'Forward To Connection' button ?
------------------------------------------------------------------------------------------------------------------------
// Define Network id String connectionName = 'SF_Bytes' List<PartnerNetworkConnection> partnerNetConList = [Select id from PartnerNetworkConnection where connectionStatus = 'Accepted' and connectionName = :connectionName]; Id networkId = partnerNetConList.get(0).Id; // Send Parent & Child (Attachment File) programatically PartnerNetworkRecordConnection newConnection = new PartnerNetworkRecordConnection( ConnectionId = networkId, LocalRecordId = '0010S00000OnyrK', SendClosedTasks = false, SendOpenTasks = false, SendEmails = true); insert newConnection;
------------------------------------------------------------------------------------------------------------------------