Sunday, June 11, 2017

I have walked into Apex Guide of SFDC to find if there are code samples for the parsing of the JSON into User defined Class in apex.Unfortunately document mentions that this can be achieved but still there were no code snippets i could find.

This blog post might help for small snippet reference to understand how we can write an apex class and structure the Constructor of the POST annotated method to achieve native parsing automatically.
Here is the Code Snippet of the Class . Note that the Request is a combination of Account and Contacts and hence we may need an inner class .

@RestResource(urlMapping='/DemoUrl/*')
global with sharing class MyRestResourcedemo{

//User defined Class

global class RequestWrapper{
Account acct;
Contact[] cons;
}

//Response Wrapper Class

global class ResponseWrapper{          
public String StatusCode;
public String StatusMessage;
public Account acct;
public Contact[] cons;  
}

@HttpPost
global static ResponseWrapper doPost(RequestWrapper reqst){
ResponseWrapper resp = new ResponseWrapper();
try{
insert reqst.acct;
for(Contact c:reqst.cons){
c.AccountId = reqst.acct.Id;
}
Upsert reqst.cons;
}
catch( Exception e ){
resp.statusCode = 'Error';
resp.statusMessage = 'Exception : ' + e.getMessage();
}
resp.statusCode = 'Done';
resp.statusMessage = 'Test success message';
resp.acct = reqst.acct;
resp.cons = reqst.cons;
return resp;
}
}
The Request Body is as shown below
{
    "reqst" :
        {
            "acct" : {
                        "Name" : "Test Account 1",
                       "AccountNumber" : "00000001",
                       "Site" : "Site1",
                       "Website" : "www.site1.com"
                     
                     },
       
            "cons":
                [
                    { "Name": "Test Contact1", "email" : "testcontact1@test.com", "LastName":"TLName2"},
                    { "Name": "Test Contact2", "email" : "testcontact2@test.com", "LastName":"TLName3"},
                    { "Name": "Test Contact3", "email" : "testcontact3@test.com", "LastName" : "TLName"}
                ]
        }
}

Monday, March 27, 2017

@IsTest
private class CaseManagerTest {

    @isTest static void testGetCaseById() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Cases/'
            + recordId;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Case thisCase = CaseManager.getCaseById();
        // Verify results
        System.assert(thisCase != null);
        System.assertEquals('Test record', thisCase.Subject);
    }

    @isTest static void testCreateCase() {
        // Call the method to test
        ID thisCaseId = CaseManager.createCase(
            'Ferocious chipmunk', 'New', 'Phone', 'Low');
        // Verify results
        System.assert(thisCaseId != null);
        Case thisCase = [SELECT Id,Subject FROM Case WHERE Id=:thisCaseId];
        System.assert(thisCase != null);
        System.assertEquals(thisCase.Subject, 'Ferocious chipmunk');
    }

    @isTest static void testDeleteCase() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Cases/'
            + recordId;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        CaseManager.deleteCase();
        // Verify record is deleted
        List<Case> cases = [SELECT Id FROM Case WHERE Id=:recordId];
        System.assert(cases.size() == 0);
    }

    @isTest static void testUpsertCase() {
        // 1. Insert new record
        ID case1Id = CaseManager.upsertCase(
                'Ferocious chipmunk', 'New', 'Phone', 'Low', null);
        // Verify new record was created
        System.assert(Case1Id != null);
        Case case1 = [SELECT Id,Subject FROM Case WHERE Id=:case1Id];
        System.assert(case1 != null);
        System.assertEquals(case1.Subject, 'Ferocious chipmunk');
        // 2. Update status of existing record to Working
        ID case2Id = CaseManager.upsertCase(
                'Ferocious chipmunk', 'Working', 'Phone', 'Low', case1Id);
        // Verify record was updated
        System.assertEquals(case1Id, case2Id);
        Case case2 = [SELECT Id,Status FROM Case WHERE Id=:case2Id];
        System.assert(case2 != null);
        System.assertEquals(case2.Status, 'Working');
    }  

    @isTest static void testUpdateCaseFields() {
        Id recordId = createTestRecord();
        // updateCaseFields() expects request parameters.
        // Set parameters in test request.
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Cases/'
            + recordId;
        request.httpMethod = 'PATCH';
        request.params.put('id', recordId);
        request.params.put('status', 'Working');
        RestContext.request = request;
        // Update status of existing record to Working
        ID thisCaseId = CaseManager.updateCaseFields();
        // Verify record was updated
        System.assert(thisCaseId != null);
        Case thisCase = [SELECT Id,Status FROM Case WHERE Id=:thisCaseId];
        System.assert(thisCase != null);
        System.assertEquals(thisCase.Status, 'Working');
    }

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Case caseTest = new Case(
            Subject='Test record',
            Status='New',
            Origin='Phone',
            Priority='Medium');
        insert caseTest;
        return caseTest.Id;
    }        

}

Thursday, February 16, 2017

How to Create Lightning Component: -

Before start coding we will see where we will write code for lightning components,

1. In developer Console --> Goto Developer Console --> select File --> New --> Lightning Component

2. we can write in ecllipse editor, but for compilation we have save that code in salesforce 

AIM : Create a simple lightning component to fetch account records and display on lightning App

Required lightning components: <Aura:Component>, <Aura:attribute>, <aura:handler>, UI Controller and apex class

Component Code:-

<aura:component controller="TechSoft.getActInfo">    
 <aura:attribute name="accountId" type="String" default=" " />
 <aura:attribute name="accountlst" type="account[]" />
 <aura:handler name="init" value="{!this}" action="{!c.getAcctInfo}" /> 
    <table>
        <thead>
           <tr><td>Account name</td><td>Account Phone</td></tr>
        </thead>
     <aura:iteration items="{!v.accountlst}" var="acct" >
        <tbody>
            <tr>               
                <td>
                    <div class="slds-truncate" title="Name">{!acct.Name}</div>
                </td>
                <td>
                    <div class="slds-truncate" title="Phone">{!acct.Phone}</div>
                </td>
            </tr>
        </tbody>    
  </aura:iteration>
    </table>    
</aura:component>

Controller.js:-  
    ({
 getAcctInfo : function(component, event, helper) {
  var action = component.get("c.getaccountData");
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state="SUCCESS"){
                var items = response.getReturnValue();
                component.set("v.accountlst",items);
            }
        });
        $A.enqueueAction(action);
 }
})

Apex Class:-

  
public class getActInfo {    
 @AuraEnabled
    public static list<account> getaccountData(){
        return [select Name, phone,AccountNumber from Account];
    }
  }

Output:-

Creating, Updating, deleting, patching and putting case record using rest api :-

Following is the same code for all the above actions,


@RestResource(urlMapping='/Cases/*')
global with sharing class KnowledgeCaseManager {
    
    @HttpGet
    global static Case getCaseById() {
        RestRequest request = RestContext.request;
        // grab the caseId from the end of the URL
        String caseId = request.requestURI.substring(
          request.requestURI.lastIndexOf('/')+1);
        Case result =  [SELECT CaseNumber,Subject,Description,Status,Origin,Priority
                        FROM Case
                        WHERE Id = :caseId];
        return result;
    }

   @HttpPost
    global static ID createCase(String subject, String status,
        String origin, String priority) {
        Case thisCase = new Case(
            Subject=subject,
            Status=status,
            Origin=origin,
            Priority=priority);
        insert thisCase;
        return thisCase.Id;
    }  

    @HttpDelete
    global static void deleteCase() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
        delete thisCase;
    }     

    @HttpPut
    global static ID upsertCase(String Subject,String Description,String Status,
        String Origin,String Priority,String id) {
        Case thisCase = new Case(
                Id=id,
                Subject=Subject,
                Description=Description,
                Status=Status,
                Origin=Origin,
                Priority=Priority);
        // Match case by Id, if present.
        // Otherwise, create new case.
        upsert thisCase;
        // Return the case ID.
        return thisCase.Id;
    }

    @HttpPatch
    global static ID updateCaseFields() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Case sObject
            thisCase.put(fieldName, params.get(fieldName));
        }
        update thisCase;
        return thisCase.Id;
    }    

}

Retrieve Data with GET Method using Workbench:

In Workbench--Workbench-->>select GET -->>
Enter the URI /services/apexrest/Cases/<Record ID>, replacing <Record ID> with the ID of the record you created in the previous step.
Click Execute.

This invocation calls the method associated with the GET HTTP method, namely the getCaseById method.

To view the response returned, click Show Raw Response.

The returned response looks similar to this response. The response contains the fields that the method queried for the new case record. 

For posting data to record using workbench: -->> reset explorer -->> Post -->> 

replace the default URI with /services/apexrest/Cases/

For the request body, insert the following JSON string representation of the object to insert.

{
  "subject" : "Bigfoot Sighting!",
  "status" : "New",
  "origin" : "Phone",
  "priority" : "Low"

To access it from other systems like java and .net we should provide the entire url path like, https://yourInstance.salesforce.com/services/apexrest/<Cases>/

Here "https://yourInstance.salesforce.com/services/apexrest/" is the base endpoint for REST API and followed by URL mapping whatever we provided to rest class in our example it is "/Cases/" mentioned on top.

Annotation  Action  Details
@HttpGet    Read    Reads or retrieves records.
@HttpPost   Create  Creates records.
@HttpDelete Delete  Deletes records.
@HttpPut    Upsert  Typically used to update existing records or create records. 

@HttpPatch  Update  Typically used to update fields in existing records.