Sunday, 7 May 2017

Reading Attachment ID's from CSV,retrieve from and Stores into the local folder using java


Here in the following example

We tried to explain how to read csv file which has attachment id's and then retrieving the related documents to local folder.
Use Case :
Developer gets one csv file with  attachment id's and those needs to be retrieved from and stores into local folder.

Please look into the comments you can uderstand the what is the code for reading id's from CSV file and qurying the same from and stores into local folder.

Import com.sforce.soap.enterprise.Connector;
Import com.sforce.soap.enterprise.EnterpriseConnection;
Import com.sforce.soap.enterprise.QueryResult;
Import com.sforce.soap.enterprise.sobject.Attachment;
Import com.sforce.soap.enterprise.sobject.Opportunity;
Import java.util.ArrayList;
Import java.util.List;
Import *;
Public class Retrieve3 {
Public static void main (String [] args) throws NumberFormatException, IOException, URISyntaxException {
/ * Reading CSV File which has attachement record Id's * /
List <String> documentIdSet = new ArrayList <String> ();
                        String csvFile = "D: /DemoFOlder/AttachmentIdSheet.csv";
String line = "";
                        String cvsSplitBy = ",";
                        Try (BufferedReader br = new BufferedReader (new FileReader (csvFile))) {
                            While ((line = br.readLine ())! = Null) {
                                // use comma as separator
                                String [] attachmentId = line.split (cvsSplitBy);

                                System.out.println ("attachmentId =" + attachmentId [0]);                            
documentIdSet.add (attachmentID [0]);
                            documentIdSet.remove (0);                        
                        } Catch (IOException e) {
                            e.printStackTrace ();
/ * End of Reading CSV File which has attachement record Id's * /
/ * Start of Retrieving the Documents from Salesforce and put them into LocalFolder * /
                    // Create a new connectionconfig to your Salesforce Org
                     ConnectorConfig sfconfig = new ConnectorConfig ();
                     // Use your salesforce username
                     sfconfig.setUsername ( "");                  
                     // Use your salesforce password with your security token look like:
                     sfconfig.setPassword ( "testXXXXXXX");                  
                     EnterpriseConnection partnercon = null;  
// create a salesforce connection object with the credentials supplied in your connectionconfig
Partnercon = Connector.newConnection (sfconfig);  
String strIds = "";
For (String ids: documentIdSet) {
((StrIds.equals "")) {if
StrIds = "'" + ids + "'";
else {
StrIds + = ", '" + ids + "'";
For (String ids: documentIdSet) {
QueryResult describeGlobalResult = partnercon.query ("select Id, Name, Body from Attachment where Id =" "+ ids +" '");
System.out.println (describeGlobalResult.getRecords () length.);              
Boolean done = false;
while (! done)
 For (int k = 0; k <describeGlobalResult.getRecords (). Length; k ++)

 Attachment a = Attachment describeGlobalResult.getRecords () [k];                    
 String fpath123 = "D: // DemoFOlder // Attachments";

 File path = new File (fpath123);
 String mySubFolder = a.getId ();          
 File newDir = new File (path + File.separator);        
 Boolean success = newDir.mkdirs ();          
 FileOutputStream fos = new FileOutputStream (newDir + File.separator + a.getId () + "-" + a.getName ());
 Fos.write (a.getBody ());
 Fos.close ();
 If (describeGlobalResult.isDone ()) {
Done = true;
 } Else {
  DescribeGlobalResult = partnercon.queryMore (describeGlobalResult.getQueryLocator ());
                     } Catch (ConnectionException e) {    
                        E.printStackTrace ();
/ * Endo of Retrieving the Documents from Salesforce and put them into LocalFolder * /

Wednesday, 2 November 2016

Getting Custom Field Id without hardcoding through Tooling API (Without Http Callout also)


We can get custom field ids for URL hacking to auto populate through Tooling API as shown below.

Apex Code:

List<FieldDefinition> fieldList =  [SELECT DurableId,QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName ='Account'and QualifiedApiName='NoofEmployees__c'];
String NoofEmployeesId = fieldList[0].DurableId.split('\\.')[1];

Visualforce Page (Java Script):

<script type="text/javascript">
            var __sfdcSessionId = '{!GETSESSIONID()}';
<script src="../../soap/ajax/38.0/connection.js" type="text/javascript"></script>
var qr = sforce.connection.query("SELECT DurableId,QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName ='Account'and QualifiedApiName='NoofEmployees__c'" );
              var NoofEmployeesId = qr.getArray("records")[0].DurableId.split('.')[1];

Thursday, 15 September 2016

Exposing an Apex Class as REST Web Service

Hi ,

We are going to learn how to write a REST webservice in

We can expose our Apex classes and methods so that external applications can access our code

and our application through the REST architecture.

 @RestResource annotation is used to expose a class as REST resource .

 Similarly we have to add annotations to methods to expose them throug REST like @HttpPost,@HttpGet etc.,

 If we add "@HttpGet" annotation for a method to expose it as a Rest resource then that can be called by Http GET request
 from external applications.

Sample Post Service:
global without sharing class StudentCreationcls {
    global static String createStudentRecord(DoctorServiceParser doctObj){
        Doctor__c doctorObj = new Doctor__c();
        doctorObj.Name =doctObj.Name;
        doctorObj.Salary__c = doctObj.Salary;
        doctorObj.Gender__c = doctObj.Gender;            
        Database.saveResult saveResult = database.insert(doctorObj,false);
            System.debug('Record Id:'+saveResult.getId());
        JSONGenerator gen=JSON.createGenerator(true);    
        gen.writeStringField('message','Doctor record is created Successfully');
        String responseString= gen.getAsString();
        return responseString;

Parser Class:
This class will be used for parsing the details in the request
global class DoctorServiceParser {

    global String Name{get;set;}
    global String FirstName{get;set;}
    global decimal consultationFee{get;set;}
    global String LastName{get;set;}
    global decimal Salary{get;set;}
    global String Gender{get;set;}

Our service endpoint will be :https://hostnamesalesforce/services/apexrest/DoctorService

Request Format for this:

We can execute this in rest Explorer of workbench for validating before we are going to give for exteranl applications.


Saturday, 3 September 2016

Excellent C ,C++ ,Java ,Photo Shop Tutorias

Hi Guys,

Please find the below url for excellent tutorials of C,C++,Java ,Photo Shop Tutorials.

Contact Details :

Sri Sai Computer Education

Phone:+91 9885094573,7386972889 ,

Andhra Pradesh (state),
India(country) -- 516001.

Saturday, 6 August 2016

Create Lead Record using Lightning Component


This example explains you how to create lead record from Lightning component.

here we did the following things

  • one apex class with aura enabled methods  which has lead insert.
  • one  Lightning component you can see previous example how to create a component
  • included lightning styles from lightning design system.
  • include controller with lightning component to invoke apex method and process
  • created one app to execute component
Apex class:

public class LightningLeadCreatecls {
    public static Id creatLeadRecord(Lead leadObj){
        upsert leadObj;


<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="LightningLeadCreatecls">
 <!--including lightning styles-->
    <ltng:require styles="{!$Resource.Lightning_slds+'/assets/styles/salesforce-lightning-design-system.css'}"/>
     <ltng:require styles="{!$Resource.Lightning_slds+'/assets/styles/salesforce-lightning-design-system.min.css'}"/>
<!-- Preparation of lead object with fields-->
    <aura:attribute name="leadObj" type="Lead"  default="{'sobjectType':'lead',
   <div class="slds">
       <div class="slds-form-element">
          <label class="slds-form-element__label" for="FirstName">First Name</label>
          <div class="slds-form-element__control">
            <ui:inputText aura:id="FirstName" class="slds-input" value="{!v.leadObj.FirstName}" placeholder="First Name" />
       <div class="slds-form-element">
          <label class="slds-form-element__label" for="LastName">Last Name</label>
          <div class="slds-form-element__control">
            <ui:inputText aura:id="LastName" class="slds-input" value="{!v.leadObj.LastName}" placeholder="Last Name" />
       <div class="slds-form-element">
          <label class="slds-form-element__label" for="Company">Company</label>
          <div class="slds-form-element__control">
            <ui:inputText aura:id="Company" class="slds-input" value="{!v.leadObj.Company}" placeholder="Company" />
       <div class="slds-form-element">
          <label class="slds-form-element__label" for="Email">Email</label>
          <div class="slds-form-element__control">
            <ui:inputText aura:id="Email" class="slds-input" value="{!v.leadObj.Email}" placeholder="Email" />
       <div class="slds-form-element">        
          <div class="slds-form-element__control">
            <ui:button label="Save" press="{!}"/>

save : function(component, event, helper) {    
    var action = component.get("c.creatLeadRecord");
            var leadId = result.getReturnValue();

<aura:application >
    <c:LeadCreation />


Sunday, 3 July 2016

Lightning Component Creation (Account List Example)

This example explains you how to create a component and place the same into the Lightning app.

To create a Lignting Component we have different tools . For now we are going to use developer console to create Component.


Give Name "AccountsComponent"
After click on "Submit" you can get the Component with Lightning Bundle at right Panel.

Now create an apex class(Server Side Controller)  with "@Auraenabled" methods which will be used in the above component.

public with sharing class B_Lightning_AccountCls {
       public static List<Account> retrieveAccounts(){
                    List<Account> accountList = new List<Account>();
accountList = [select id,name,AnnualRevenue,Industry,Website  from Account limit 5];
                   return accountList;

Now include the controller in the component by using "controller" attribute.

<aura:component controller="B_Lightning_AccountCls">

Use <aura:atrribute> tag to hold the values from the javascript controller .

<aura:attribute name="Accounts" type="Account[]"/>

Here the "init" handler  used for performing action when component initialized.

<aura:handler name="init" action="{!c.myAction}" value="this"/> 

Here "myAction" is  a method in "controller" which we can create from the "controller" in lightning bundle  .
Component Code:

<aura:component controller="B_Lightning_AccountCls">
    <ltng:require styles="{!$Resource.Lightning_slds+'/assets/styles/salesforce-lightning-design-system.css'}"/>
     <ltng:require styles="{!$Resource.Lightning_slds+'/assets/styles/salesforce-lightning-design-system.min.css'}"/>
    <aura:attribute name="Accounts" type="Account[]"/>
      <aura:handler name="init" action="{!c.myAction}" value="this"/>
    <div class="container">
        <div class="slds">
            <ul class="slds-has-dividers--around-space">
                <li class="slds-item">
                    <div class="slds-tile slds-tile__detail">
                      <strong>Accounts Info</strong>
                <aura:iteration  items="{!v.Accounts}" var="accountObj">
                     <li class="slds-item">
                        <div class="slds-tile slds-tile--board">
                          <p class="slds-truncate" title="Anypoint Connectors"><a href="javascript:void(0);">{!accountObj.Name}</a></p>
                          <div class="slds-tile__detail slds-text-body--small">
                            <p class="slds-text-heading--medium">{!accountObj.AnnualRevenue}</p>
                            <p class="slds-truncate"><a href="javascript:void(0);">{!accountObj.Website}</a></p>
                            <p class="slds-truncate">{!accountObj.Industry}</p>

Click on "Controller" to create method.

Controller Code:

myAction : function(component, event, helper) {
var  action = component.get("c.retrieveAccounts");

var  action = component.get("c.retrieveAccounts"); //This is used for invoking the method 

Now we have completed component creation.

Now create a lighning app to see our output:


Now Give Name "AccountsApp" for application:

Click on Submit  and then we can see app with the following tag:

Now include your component by using "<c:componentName/>

Note the if we are creating package use package namespace in the place of "c" for specifying the component.

Here baluPckage is the name space.

To see your out put click on "Preview" in the Application right panel as shown below.