Monday, February 6, 2012

Calling of web service from Java script using Ajax

Here is the web service link: Currency Convertor 

HTML code:

<html>
<head>
<script type="text/javascript">
    function WebSvc()    
    {
        WebSvc.prototype.CallWebService = function(url, soapXml, callback)
        {
            var xmlDoc = null;
            if (window.XMLHttpRequest)
            {
                xmlDoc = new XMLHttpRequest(); //Newer browsers
            }
            else if (window.ActiveXObject) //IE 5, 6
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
            }

            if (xmlDoc)
            {
                //callback for readystate when it returns
                var self = this;
                xmlDoc.onreadystatechange = function() { self.StateChange(xmlDoc, callback); };

                //set up the soap xml web service call
                xmlDoc.open("POST", url, true);
                xmlDoc.setRequestHeader("Content-Type", "text/xml");
                xmlDoc.setRequestHeader("Content-Length", soapXml.length);
                xmlDoc.send(soapXml);
            }
            else
            {
                if (callback)
                {
                    callback(false, "unable to create XMLHttpRequest object");
                }
            }
        };
        WebSvc.prototype.StateChange = function(xmlDoc, callback)
        {
            if (xmlDoc.readyState === 4)
            {
                var text = "";
                if (xmlDoc.status === 200)
                {
                    text = xmlDoc.responseText;
                }
                if (callback !== null)
                {
                    callback(xmlDoc.status === 200, text);
                }
            }
        };
    }
    function callComplete(result, data)
    {
        if (result)
        {
            document.getElementById("res").innerHTML=getTagValue(data, "ConversionRateResult");
        }
        else
        {
            alert("Error occurred calling web service.");
        }
    }
    function getTagValue(inputStr, tagName)
    {
        var stag = "<" + tagName + ">";
        var etag = "</" + tagName + ">";
        var startPos = inputStr.indexOf(stag, 0);
        if (startPos >= 0)
        {
            var endPos = inputStr.indexOf(etag, startPos);
            if (endPos > startPos)
            {
                startPos = startPos + stag.length;
                return inputStr.substring(startPos, endPos);
            }
        }
        return "";
    }
    function getTime()
    {
        var soap = createSoapHeader();
        var webServiceCall = new WebSvc();
        webServiceCall.CallWebService("http://www.webservicex.net/CurrencyConvertor.asmx?wsdl",soap, callComplete); 
    }
    function createSoapHeader()
    {
        var soap = "<soapenv:Envelope xmlns:soapenv="+"\"http://schemas.xmlsoap.org/soap/envelope/\""+" xmlns:web="+"\"http://www.webserviceX.NET/\""+"><soapenv:Header/><soapenv:Body><web:ConversionRate><web:FromCurrency>USD</web:FromCurrency><web:ToCurrency>INR</web:ToCurrency></web:ConversionRate></soapenv:Body></soapenv:Envelope>";
        return soap;
    }
</script>
</head>
<body>
<button type="button" onclick="getTime()">Click Me</button>
<div id="res"></div>
</body>
</html>


Querying Account details using Salesforce Connection.js


<apex:page standardController="case">
<script src="/soap/ajax/23.0/connection.js" type="text/javascript"></script>
<script type="Text/javascript">
sforce.connection.login("prakumar123@progress.com", "welcome123KfENXmgve3IefdHP5ZNr2f9Gc");
function setupPage()
{
var qry="Select Id, Name, Industry From Account";
var result=sforce.connection.query(qry,layoutResults);
}
function layoutResults(queryResult, source)
{
if (queryResult.size > 0)
{
var output = "";
var records = queryResult.getArray('records');
for (var i = 0; i < records.length; i++)
{
var account = records[i];
output += account.Id + " " + account.Name +" [Industry - " + account.Industry + "]<br>";
document.getElementById("out").innerHTML=output;
}
}
}
</script>
<apex:pageBlock >
<input type="button" Title="Get Accounts" Value="Click me" OnClick="setupPage()"/>
<div id="out">test</div>
<apex:includeScript value="/soap/ajax/23.0/connection.js"/>
</apex:pageBlock>
</apex:page>

Monday, January 30, 2012

Case History Related List

Component VF Code:


<apex:component controller="CaseHistoriesComponentController">
    <!-- Attribute Definition -->
    <apex:attribute name="CaseId" description="Salesforce Id of the Case whose Case History needs to be rendered" type="Id" required="true" assignTo="{!caseId}" />
    
    <!-- Case History Related List -->
    <apex:pageBlock title="Case History">
        <apex:pageBlockTable value="{!histories}" var="History" >
            <apex:column headerValue="Date"  value="{!History.thedate}"/>
            <apex:column headerValue="User"> <apex:outputLink value="/{!History.userId}"> {!History.who} </apex:outputLink></apex:column>
            <apex:column headerValue="Action"><apex:outputText escape="false" value="{!History.action}"/></apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:component>


Controller Code:



public class CaseHistoriesComponentController {
    
    public Id caseId {get; set;}
    public cHistories[] histories; 
    
    // Variables
    public Static final Map<String, Schema.SObjectField> CaseFieldmap = Schema.SObjectType.Case.fields.getMap();
    public Static final List<Schema.PicklistEntry> fieldPicklistValues = CaseHistory.Field.getDescribe().getPicklistValues();
    
    public List<cHistories> getHistories()
    {
        list<cHistories> histories = new list<cHistories>();
        String prevDate = '';
        for(CaseHistory cHistory : [Select CreatedDate, CreatedBy.Name, CreatedBy.Id, Field, NewValue, OldValue from CaseHistory where CaseId = :caseId order by CreatedDate desc])
        {
            if((cHistory.newValue == null && cHistory.oldValue == null) 
                    || (cHistory.newValue != null && !(string.valueOf(cHistory.newValue).startsWith('005') || string.valueOf(cHistory.newValue).startsWith('00G')))
                    || (cHistory.oldValue != null && !(string.valueOf(cHistory.oldValue).startsWith('005') || string.valueOf(cHistory.oldValue).startsWith('00G'))))
            {
                cHistories tempHistory = new cHistories();
                // Set the Date and who performed the action
                if(String.valueOf(cHistory.CreatedDate) != prevDate)
                {
                    tempHistory.theDate = String.valueOf(cHistory.CreatedDate);
                    tempHistory.who = cHistory.CreatedBy.Name;
                    tempHistory.userId = cHistory.CreatedBy.Id;
                }
                else
                {
                    tempHistory.theDate = '';
                    tempHistory.who = '';
                    tempHistory.userId = cHistory.CreatedBy.Id;
                }
                prevDate = String.valueOf(cHistory.CreatedDate);
                
                // Get the field label
                String fieldLabel = CaseHistoriesComponentController.returnFieldLabel(String.valueOf(cHistory.Field));
                
                // Set the Action value
                if (String.valueOf(cHistory.Field) == 'created') {    // on Creation
                    tempHistory.action = 'Created.';
                }
                else if(cHistory.OldValue != null && cHistory.NewValue == null){ // when deleting a value from a field
                    // Format the Date and if there's an error, catch it and re
                    try {
                        tempHistory.action = 'Deleted ' + Date.valueOf(cHistory.OldValue).format() + ' in <b>' + fieldLabel + '</b>.';
                    } catch (Exception e){
                        tempHistory.action = 'Deleted ' + String.valueOf(cHistory.OldValue) + ' in <b>' + fieldLabel + '</b>.';
                    }
                }
                else{  // all other scenarios
                    String fromText = '';
                    if (cHistory.OldValue != null) {
                        try {
                            fromText = ' from ' + Date.valueOf(cHistory.OldValue).format();
                        } catch (Exception e) {
                            fromText = ' from ' + String.valueOf(cHistory.OldValue);
                        }
                    }
                    
                    String toText = '';
                    if (cHistory.OldValue != null) {
                        try {
                            toText = Date.valueOf(cHistory.NewValue).format();
                        } catch (Exception e) {
                            toText = String.valueOf(cHistory.NewValue);
                        }
                    }
                    if(toText != '')
                        tempHistory.action = 'Changed <b>' + fieldLabel + '</b>' + fromText + ' to <b>' + toText + '</b>.';
                    else
                        tempHistory.action = 'Changed <b>' + fieldLabel;
                }
                
                // Add to the list
                histories.add(tempHistory);
            }
        }
        
        return histories;
    }   
    
    // Function to return Field Label of a Case field given a Field API name
    public Static String returnFieldLabel(String fieldName)
    {
        if(CaseHistoriesComponentController.CaseFieldmap.containsKey(fieldName))
            return CaseHistoriesComponentController.CaseFieldmap.get(fieldName).getDescribe().getLabel();
        else
        {
            for(Schema.PicklistEntry pickList : fieldPicklistValues)
            {
                if(pickList.getValue() == fieldName)
                {
                    if(pickList.getLabel() != null)
                        return pickList.getLabel();
                    else
                        return pickList.getValue();
                }
            }
        }
        return '';
    }
    // Inner Class to store the detail of the case histories    
    public class cHistories {


        public String theDate {get; set;}
        public String who {get; set;}
        public Id userId {get; set;} 
        public String action {get; set;}
    }
}

Case Comment Related List

Component VF Code:


<apex:component controller="CaseCommentsComponentController" allowDML="true">
    <!-- Attribute Definition -->
    <apex:attribute name="CaseId" description="Salesforce Id of the Case whose Case Comments needs to be rendered" type="Id" required="true" assignTo="{!caseId}" />
    
    <!-- Component Body -->
    <apex:componentBody >
        <apex:form >
            <apex:pageBlock title="Case Comments" >
                <apex:pageBlockButtons location="top">
                    <apex:commandButton action="{!NewComment}" value="New"/>
                </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!Comments}" var="comment"> 
                    <apex:column headerValue="Action"> 
                        <apex:outputLink value="/{!comment.cComment.Id}/e?parent_id={!caseId}&retURL=/{!caseId}">Edit</apex:outputLink>&nbsp;&nbsp;
                        <apex:commandLink action="{!deleteComment}" value="Del">
                            <apex:param name="CommentId_d" value="{!comment.cComment.Id}"/>
                        </apex:commandLink>&nbsp;&nbsp; 
                        <apex:commandLink action="{!makePublicPrivate}" value="{!comment.PublicPrivateAction}">
                            <apex:param name="CommentId_p" value="{!comment.cComment.Id}" />
                        </apex:commandLink>
                    </apex:column>
                    <apex:column headerValue="Public" value="{!comment.cComment.IsPublished}" />
                    <apex:column headerValue="Comments">
                        <apex:outputText escape="false" value="{!comment.commentText}"/>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>   
        </apex:form>    
    </apex:componentBody>
</apex:component>


Controller Code:


public with sharing class CaseCommentsComponentController {
    
    public Id caseId {get; set;}
    public cComments[] comments{
        get{
            List<cComments> comments = new List<cComments>();
            for(CaseComment comment : [Select LastModifiedDate, LastModifiedBy.Id, LastModifiedBy.Name, IsPublished, CreatedDate, CreatedBy.Id, CreatedBy.Name, CommentBody From CaseComment c where ParentId = :caseId order by c.LastModifiedDate desc])
            {
                cComments tempcComment = new cComments();
                tempcComment.cComment = comment;
                
                // Build String to display.
                tempcComment.commentText = '<b>Created By: <a href=\'/' + comment.CreatedBy.Id + '\'>' + comment.CreatedBy.Name + '</a> (' + comment.CreatedDate.format() + ') | ';
                tempcComment.commentText += 'Last Modified By: <a href=\'/' + comment.LastModifiedBy.Id + '\'>' +  comment.LastModifiedBy.Name + '</a> (' + comment.LastModifiedDate.format() + ')</b><br>';
                tempcComment.commentText += comment.CommentBody;
                
                if(comment.IsPublished)
                    tempcComment.PublicPrivateAction = 'Make Private';
                else
                    tempcComment.PublicPrivateAction = 'Make Public';
                //Add to list
                comments.add(tempcComment); 
            }
            return comments;
        }
        
        set;
    }
        
    public PageReference NewComment()
    {
        PageReference pr = new PageReference('/apex/new_comment?id='+caseId);
        pr.setRedirect(true);
        return pr;
    }
    
    public PageReference deleteComment()
    {
        Id commentId = ApexPages.currentPage().getParameters().get('CommentId_d');
        
        for(cComments Comment : comments)
        {
            if(Comment.cComment.Id == commentId)
            {   
                delete Comment.cComment;                
                break;
            }
        }
        
        PageReference pg = new PageReference('/' + caseId);
        pg.setRedirect(true);
        return pg;
    }   
    
    public PageReference makePublicPrivate()
    {
        Id commentId = ApexPages.currentPage().getParameters().get('CommentId_p');
        for(cComments Comment : comments)
        {
            if(Comment.cComment.Id == commentId)
            {   
                Comment.cComment.IsPublished = !Comment.cComment.IsPublished;
                if(Comment.cComment.IsPublished)
                    Comment.PublicPrivateAction = 'Make Private';
                else
                    Comment.PublicPrivateAction = 'Make Public';
                    
                update Comment.cComment;                
                break;
            }
        }
        PageReference pg = new PageReference('/' + caseId);
        pg.setRedirect(true);
        return pg;
    }
    
    public class cComments {
    
        public CaseComment cComment {get; set;}
        public String commentText {get; set;}
        public String PublicPrivateAction {get; set;}
    }
}