anusha(salesforce developer)

Thursday, 19 January 2017

What is web services?

A web service is a piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for the corresponding XML response.

There are mainly two types of web services.

    1. SOAP web services.
    2. RESTful web services.

Components of Web Services

    • SOAP (Simple Object Access Protocol)
    • UDDI (Universal Description, Discovery and Integration)
    • WSDL (Web Services Description Language)

Soap web services: – SOAP is XML based protocol. It is platform and language independent. By using SOAP, you will be able to interact with other applications designed in different programming languages.
Rest web services: – REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications, it is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service.

Difference between SOAP and REST

No.SOAPREST
SOAP stands for Simple Object Access Protocol.REST stands for Representational State Transfer.
SOAP is a XML based messaging protocol.REST is an architectural style.
SOAP permits XML data format only.REST permits different data format such as Plain text, HTML, XML, JSON etc.
SOAP defines standards to be strictly followed.REST does not define too much standards like SOAP.
JAX-WS is the java API for SOAP web services.JAX-RS is the java API for RESTful web services.
SOAP is distributed computing style.REST is web style (web is also a distributed computing model).

REST Web Service

REST stands for Representational State Transfer. REST was a term coined by Roy Fielding.
REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol.
Using HTTP Methods for RESTful Services
HTTP VerbCRUD
GETRead
PUTUpdate/Replace
PATCHUpdate/Modify
DELETEDelete

Features of a RESTful Services: – A Restful web service should have following features.
    • Representations
    • Messages
    • URIs
    • Uniform interface
    • Stateless
    • Links between resources
    • Caching

Representations
“The focus of a RESTful service is on resources and how to provide access to these resources. A resource can easily be thought of as an object as in OOP. A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other. This is similar to the first step of designing a database: Identify entities and relations”.
In Rest we can use any format for representing our resources, as Rest does not put a restriction on the format of representation.
We can use either JSON format or XML format to represent our resource.
If you are building Web services that will be used by Web pages for AJAX calls, then JSON is a good choice. XML can be used to represent more complex resources.
Example 1
JSON representation of a resource
 




{ "ID": "001",
"Name": "Anil Singh",
"Email": "xxx.anil354@gmail.com",
"Country": "India"
}
Example 2
XML representation of a resource
<Person><ID>001</ID><Name>Anil Singh</Name><Email>xxx.anil354@gmail.com </Email><Country>India</Country></Person>

Note:-“The representation should be capable of linking resources to each other. This can be done by placing the URI or unique ID of the related resource in a representation”.

Message
“The client and service talk to each other via messages. Clients send requests to the server, and the server replies with a response. Apart from the actual data, these messages also contain some metadata about the message”.

Caching
“Caching is the concept of storing the generated results and using the stored results instead of generating them repeatedly if the same request arrives in the near future. This can be done on the client, the server, or on any other component between them, such as a proxy server. Caching is a great way of enhancing the service performance, but if not managed properly, it can result in client being served stale results”.

Statelessness
“A RESTful service is stateless and does not maintain the application state for any client. A request cannot be dependent on a past request and a service treats each request independently”.

Uniform Interface
“The uniform interface constraint is fundamental to the design of any REST service. The uniform interface simplifies and decouples the architecture, which enables each part to evolve independently”.

Links between resources
“A resource representation can contain links to other resources like an HTML page contains links to other pages. The representations returned by the service should drive the process flow as in case of a website. When you visit any website, you are presented with an index page. You click one of the links and move to another page and so on. Here, the representation is in the HTML documents and the user is driven through the website by these HTML documents themselves. The user does not need a map before coming to a website. A service can be (and should be) designed in the same manner”.

what is View State and how can we avoid these View State error?

View State:  As the name suggests, is an error of View State. “Maximum view state size limit (135KB) exceeded” is the error message pertaining to “View State” error and here follows a brief detailing of the issue.
View state holds the state/size of the visual force page that includes the components, field values and controller state. This is important in the light that salesforce provides only a standard size of 135kb for any individual page. If the size of a particular page exceeds 135kb, the page will throw a view state error.
To check the view state of a visual force page you have to make sure that ‘’Show View State in Development Mode’’ checkbox in the User Layout is checked.
You can access this setting from: Setup-> Manage User-> User-> Edit (on a particular user)-> Show View State in Development Mode
How to reduce View state:
1 :  Use the transient keyword : The simplest and the most logical way is to keep the size of the VF page as small as possible. For this purpose, Transient Variables are used as these do not store the values permanently, these variables just hold the values temporarily and therefore not stored in View State.
Declaring variables as transient reduces view state size.
An Example showing how a transient variable is declared:
transient String name;
2: Refine your SOQL: Reduce the number of records displayed on a page by refining SOQL. The use of AND statements, WHERE clause in SOQL, removing NULL results can help assure that only required data comes back from SOQL.
3: Minimize the Number of Forms on a Page: We should use <apex:actionReagion> instead of using two <apex:forms>.
Each form on your page will have its own copy of view state. Instead of having multiple forms on a page, have a single form and use <apex:actionRegion> to submit portions of the form.
This will make sure only a single copy of the view state is associated with that VF page instead of two copies.
Eg:
// Using two <apex:form>
<apex:page controller=”ApexController”>
      <apex:form>
         <apex:commandButton action=”{!objectFirstMethod}” value=”First Object”/> </apex:form>
      <apex:form>
      <apex:commandButton action=”{!objectSecondMethod}” value=”Second Object”/>
      </apex:form>
</apex:page>
// Using <apex:actionRegion>
<apex:page controller=”ApexController”>
      <apex:form>
       <apex:commandButton action=”{!objectFirstMethod}” value=”First Object”/>
       <apex:actionRegion>
        <apex:commandButton action=”{!objectSecondMethod}” value=”Second Object”/>
       </apex:actionRegion>
      </apex:form>
</apex:page>
4: Use Custom Setting: Use custom setting to store large quantities of read-only data instead of custom objects. Accessing custom settings is faster than accessing custom objects since custom settings are part of application’s cache and does not require a database query to retrieve the data unlike custom objects.
5: Use <apex:outputLink> : Instead of using <apex:commandLink> or <apex:commandButton> components, Use <apex:outputLink> because <apex:commandLink> or <apex:commandButton> requires to be included inside a <apex:form> component unlike <apex:outputLink>

Thursday, 5 January 2017

Deletion of account record should fail it has any contact records

 Deletion of account record should fail it has any contact records


trigger example6 on Account (before delete) {
    List<Account> accs=[select id,(Select id from Contacts) from Account where Id In:Trigger.Old];
    for(Account a:accs){
        if(a.contacts.size() > 0){
            a.addError('Account Record with contact can not be deleted');
        }
    }
}

1. Create a Custom Field No_Of_Contats on Account Object 2. When ever new Contact is created or deleted update the no_of_contacts fields with no of contacts that exits for the parent records

1. Create a Custom Field No_Of_Contats on Account Object 

2. When ever new Contact is created  or deleted update the 
 no_of_contacts fields with no of contacts that exits for the parent records


trigger contactsTriggers on Contact (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter)
        TriggerContact.increment(Trigger.New);
    else
        TriggerContact.increment(Trigger.Old);

}


public class TriggerContact {
    public static void increment(List<Contact> cons){
        set<Id> accid=new Set<id>();
        for(Contact c:cons){
           accId.add(c.AccountId); 
        }
       List<Account> accs=[select id,No_of_contacts__c ,(select id from Contacts ) from Account where id in:accId];
        for(Account a:accs){
            a.no_of_contacts__c=a.contacts.size();
        }
        update accs;
    }

}

Sunday, 1 January 2017

Adding lightning application in vf page

Adding lightning application in vf page:

<aura:application access="GLOBAL" extends="ltng:outApp"> 
    <aura:dependency resource="ui:button"/>
</aura:application>

VF Page :

<apex:page>
    <apex:includeLightning />

    <div id="lightning" />

    <script>
        $Lightning.use("c:app15", function() {
        $Lightning.createComponent("ui:button",{ label : "Press Me!" },
                                   "lightning",function(cmp) {});
        });
    </script>
</apex:page>

Monday, 12 December 2016

Create a dynamic soql query using ajax to fetch all the account records whose industry is matching with input value and display the account names

Create a dynamic soql query using ajax to fetch all the account records  whose industry is matching with input value and display the account names 

<apex:page id="page">
    <script src="/soap/ajax/36.0/connection.js" type="text/javascript">
    </script>
    <script>
    function callme(){
    sforce.connection.sessionId='{!$API.session_Id}';
            var myIndustry=document.getElementById('page:fm:myIndustry').value;
        var query='select name ,industry from Account where industry=\''+myIndustry+'\'';
    var queryResult=sforce.connection.query(query);
    var records=queryResult.getArray('records');
    var result='';
    for(var i=0;i<records.length;i++){
            result=result+'<br/>'+records[i].Name;
        }
           document.getElementById('page:fm:res').innerHTML=result;
        }         
    </script>
    <apex:form id="fm">
        <apex:inputText id="myIndustry" />
    <apex:commandButton  value="Ajax Call" oncomplete="callme()"/>
        <apex:outputLabel id="res" />
    </apex:form>
</apex:page>

BatchApexExam

Global class BatchApexExam implements database.batchable<Sobject>
{


    global database.querylocator start(database.batchablecontext bc){
            
         string query='select id, description from account';
         
        return database.getquerylocator(query);
    }
    
    global void execute(database.batchablecontext bc, list<account> acclist){
    
            for(account a: acclist){
                
                a.description='Batchapex';
            }
            
            update acclist;
    }
    global void finish(database.batchablecontext bc){
    
    }
    
}

Tuesday, 8 November 2016

Outbound email example:

How to write a code for outbound emailing?

public class OutboundExample {
    public Messaging.SingleEmailMessage email1 ;
    String[] toadd ;
    String[] tocc;
    string subject;
    public OutboundExample(){
        email1=new Messaging.SingleEmailMessage();
        toadd=new String[]{'creativetraining@gmail.com'};
        tocc=new String[]{'onlinebatch135@gmail.com'};
    }
    public void plaintTextBody(){
        email1.setToAddresses(toadd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setPlainTextBody('This is a text body');
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
    public void htmlBody(){
        email1.setToAddresses(toadd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setHtmlBody('<h3> Hai Satish</h3><font style="color:blue">This is test mail</font>');
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
    public void sendAttachments(){
        Contact c=[select id,Email from Contact where phone='9988'];
        String[] toAdd=new String[]{c.email};
        email1.setToAddresses(toAdd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setHtmlBody('<h3> Hai Satish</h3><font style="color:blue">This is test mail</font>');
        PageReference p=Page.page1;
        Blob body=P.getContentAsPDF(); 
        Messaging.EmailFileAttachment attach=new Messaging.EmailFileAttachment();
        attach.setBody(body);
        attach.setFileName('Jan-Feb-Bill.pdf');      
        Messaging.EmailFileAttachment[] attachments=new Messaging.EmailFileAttachment[]{attach};
    email1.setFileAttachments(attachments);   
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    /* Creating  Attachment with with email attachment    
        Attachment at=new Attachment();
        at.ParentId=c.id;
        at.body=body;
        at.Name='Jan-feb-Bill';
        insert at;
    */
     }
     public void sendTemplate(){        
        EmailTemplate et=[select id from EmailTemplate where name='Test'];
        email1.setTemplateId(et.id);    
        Contact c=[select id from Contact where phone='9988'];
        email1.setTargetObjectId(c.id);    
        Payment__c p=[select id from Payment__c limit 1];
        email1.setWhatId(p.id);      
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
     }
    public void massEmail(){
        Messaging.MassEmailMessage email1=new Messaging.MassEmailMessage();
      EmailTemplate et=[select id from EmailTemplate where name='Test'];
        email1.setTemplateId(et.id);
        Contact c=[select id,Email from Contact where phone='9988'];
        email1.setTargetObjectIds(new Id[]{c.id});
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
   
}

Tuesday, 18 October 2016

what is External Lookup Relationship in salesforce

Use an external lookup relationship when the parent is an external object.

An external lookup relationship links a child standard, custom, or external object to a parent external object.

When you create an external lookup relationship field, the values of the standard External ID field on the parent external object are matched against the values of the external lookup relationship field. For a child external object, the values of the external lookup relationship field come from the specified External Column Name.

Steps to create external lookup relationship:

1. Go to Setup --> Develop --> External Data Sources and create External Data Source.


2. Go to Setup --> Develop --> External Objects and create External Object.


3. Go to Setup --> Create --> Objects and select the object under which you want to create external lookup relationship.



Thursday, 29 September 2016

Difference between Public Group and Queue

Difference between Public Group and Queue


QueuePublic Group
Queues are used primary as Owners of records.Public Groups are used primary for security.
Queue is a feature available to salesforce.com users that allows you to integrate prospect assignments with your current salesforce.com workflow. Rather than assigning to a specific user, you can choose to assign leads to a salesforce.com queue and then use your CRM workflow or manual method of distributing leads to sales representatives.Public Group is kind of team or group of related users; this will help to share the data.
Queue can be created for Custom objects and for Case, Lead and Knowledge Article Version.Public group created can be used across any objects.