Thursday, May 30, 2013

To add Javascript to Standard Pagelayout in Salesforce, add a HTML Home page Component with HTML checkbox checked.


Sample Javascript:

<style type="text/css">
#popup
{
display:none;
position:absolute;
height:100px;
width:100px;
background:#E6E6FA;     
border: 2px solid black;
overflow:auto;
}
#cls
{
color:red;
text-align:right;
}
</style>

<script type="text/javascript" src="/soap/ajax/22.0/connection.js"></script>

<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready( function(){

        $(".dataCell").click(function(event){   
            $("#popup").css( {position: "absolute", top:event.pageY - 110, left: event.pageX});
            var temp = $(this).prev(".dataCell").find("a").attr("href");
            var depLink = temp.substring(1);           
            var qryString = "SELECT Description__c FROM Dependent__c where Id = '" + depLink + "'";
            sforce.connection.sessionId = getCookie('sid');
            var soql = qryString.toString();
           
            var result = sforce.connection.query(soql);   
           
            var records = result.getArray("records");
            for (var i = 0; i < records.length; i++)
            {
                var taskRecord = records[i];
                $("#cont").html(taskRecord.Description__c);
            }           
           
            showBox();
        });

        $("#cls").click(function(){
            hideBox();
        });

        function showBox()
        {
            $('#popup').fadeIn("slow");
        }
        function hideBox()
        {
            $('#popup').fadeOut("slow");
        }
    });
</script>
<div id="popup">
    <div id="cls">
    <a href="#" style="color:red;">X</a><br/>
    </div>
    <div id="cont"></div>
</div>


Output:


Wednesday, May 29, 2013

Calling External Web Services from Salesforce.com – Part III: Building an Apex class that calls your web service

Part I: Hosting your web service
Part II: Opening your web service to the internet
Part III: Building an Apex class that calls your web service

In Part I & Part II of this series, I discussed the details of hosting a web service on your computer and exposing it to the internet. If you are working in an enterprise/corporate network environment, your web service is almost always not exposed to the internet. If so, I would encourage you to also read Part I & II of this series, so you get a basic idea on how to expose your web service so that Salesforce can connect to it. In this part, we will do the fun stuff – building an Apex class that can call this web service. Before we proceed, let us revise what happens when Salesforce calls our web service -

image

1 – Our custom Apex class hosted on the Salesforce.com platform makes an outbound web service call.
2 – The call reaches our modem that forwards it to the wireless router.
3 – Since port forwarding is turned on, the router then forwards the request to our computer’s IP Address.
4 - The computer’s firewall intercepts the request, and since we opened port 80 on the firewall, lets it pass through.
5 – The IIS on the computer receives the web service request, and services it.

Now that we have the basics cleared off, let’s get into the specifics – here are step-by-step instructions on building an Apex class that calls your web service :-

  • First, we need to get the WSDL file for our web service. The WSDL(Web service definition language) file is an XML-based representation of our web service – what methods it contains, data types of method parameters, return types, and the communication protocol related details.
  • To get the WSDL, simply open a browser and navigate to your web service, passing in ?wsdl as a query string parameter. For my web service, I navigated to http://localhost/MyWebService/Service1.asmx?wsdl (if you haven’t yet hosted the web service on your computer, read Part I of this article series.
  • If your web service is hosted correctly, you should see a block of XML in your browser window. Save this as a file with .wsdl extension.
  • Next, log into Salesforce.com, and go to Setup->Develop->Apex Classes. A list of classes shows up. Here, click on the “Generate from WSDL” button.

image

image

  • On the next screen, click the “Choose File” button, and select the WSDL file you had saved previously. Click the “Parse WSDL” button to check the validity of the WSDL file.
  • Did you get an error saying “Error: Failed to parse wsdl: Found more than one wsdl:binding. WSDL with multiple binding not supported” ? Well, that happens because the WSDL file generated for an Asp.Net web service has multiple bindings.
  • Let me get into a little more detail – if you open and inspect the WSDL file, you will see a <wsdl:binding> element. The binding element defines how to use the web service with a particular protocol (e.g. http), the XML encoding, the name of the operation, input/output parameters etc. For some reason, an asp.net web service WSDL file has multiple nodes for bindings. I don’t know why it does that – both nodes appear the same to me, so I don’t see the point of repeating the same information twice. Anyway, this confuses Salesforce.com when we try to import the WSDL to create an Apex class.

image

image

  • So, we do what any good software engineer would do – remove the extra binding and proceed :). So go ahead, delete the second <wsdl:binding> node. Also remove the corresponding <wsdl:port> node that was using this binding. Try parsing the file again in Salesforce.com – this should go through without errors. When it asked for Apex class name, I used “MyWebServiceApex”.
  • Navigate to the Apex class (MyWebServiceApex), and check out the code. Specially note my notes about using the correct IP Address – I cannot stress this enough. By default, Salesforce.com uses http://localhost as the address for the web service – you need to edit that in the class to make sure it is connecting to your web service.

image 

Adding a Remote Endpoint

  • Before we run the code to call our web service, we also need to let Salesforce know that this web service could be trusted. For this, we define a “Remote Site” – go to Setup->Administration setup->Security Controls->Remote Site Settings.
  • Enter your web service address etc. here, and give it a unique name.

image

  • Now you can start testing your web service.

Testing our class via Anonymous blocks

  • Next, we will test the class we just created – launch the developer console (Setup->Developer console). Locate the “Execute” text block at the top – this is where we can put our anonymous code block.

image

  • Copy-Paste the below code into the anonymous code block -
Code Snippet
  1. MyWebServiceApex.Service1Soap s1 = new MyWebServiceApex.Service1Soap();
  2. String result;
  3. result = s1.HelloWorld();
  4. System.Debug(result);
  • When you execute the code, make sure to check the “Open Log” checkbox. This will launch your execution log file as soon as your anonymous block is executed. The piece of code here basically reaches out to the web service hosted on your computer, and invokes the “HelloWorld()” web method.

image

  • Verify the log file, and you should see the output of your “System.Debug” statement in the logs :-

image

So, these were the steps you can follow to invoke your web service from Salesforce.com. This approach has various applications – you could build an “event” mechanism so that external systems are alerted whenever something happens in Salesforce.com. Or, you could build an external logging facility that logs each and every page visit to an external database. We will explore some of the additional complexities of this process in the next post.

Calling External Web Services from Salesforce.com – Part II: Opening your web service to the internet

Part I: Hosting your web service
Part II: Opening your web service to the internet
Part III: Building an Apex class that calls your web service

I have to be honest – I did not know how to do this. Having always programmed in an enterprise environment, I never gave it a thought on hosting something that is open to the internet. Fine, everybody can’t know everything, right ? Anyways, I figured there would be others as ignorant as I am (was :)), so here’s step-by-step instructions on exposing your webservice to  the internet.

  • Disclaimer – the below description is for a specific setup – where you are on a home computer with a wireless router. Be prepared to adjust the process if your setup is different.
  • First, make sure you do this on your home computer, or a place where you have full control over the network setup, environment etc.
  • We will be using port forwarding to open up the web service hosted on the IIS on your machine to the internet. To understand what is port forwarding, start by looking at the diagram below. Your home computer is actually hosted behind a few things – firewall, modem, maybe a wireless router.
  • This ensures that nothing on the internet can directly connect to your computer. It will always have to go through the modem, and the firewall. If any malicious attempt is made, the firewall will block it. The exact details are much more sophisticated than this, but this much suffices for what we are trying to do.

image

  • This setup also affects the IP address of your computer. Open command prompt (Start->{type cmd}), and run “ipconfig”. Notice your IP Address - it will be something like 192.168.1.3. This is not a real IP address on the internet – instead, it is the “internal” IP address assigned to your computer by your modem.
  • So what is your real IP address ? Go to http://www.whatsmyip.org/ – this will show your real IP address. I found mine- it was 75.123.65.169. This again is a temporary IP address – the internet service provider can switch it at any time.

image

  • Given that the modem is our “face” to the internet, any request that comes to the IP Address 75.123.65.169 is routed to my modem. The modem may choose to either discard the request, OR, it may choose to forward the request to specific devices connected to it.
  • This is where port forwarding comes in – we basically “tell” the modem/router to forward any requests that come in from the internet on a specific port, to our computer. If we turn this on for port 80, which is used by web services, it means that any incoming web service call will be forwarded to our computer.
  • Enabling port forwarding is different for each setup, so I will walk you through what I did, and leave it to you to fill in the gaps for your particular network setup. First, I opened the administration page for my wireless router- this can be usually accessed by using the first 3 digits of your IP address + 1. For e.g., in my case, since my computer’s IP was 192.168.1.3, I opened my wireless router admin screen by visiting http://192.168.1.1 in the browser.
  • It may ask you for username/password – username is usually “admin”, you will need to know the password here – I did not know of any other way around it.
  • Once you are logged in, the screen looks like this for me:-

image

  • Next, I went to the “Advanced” tab –> “Advanced Settings” –> Port forwarding”. Here I configured it forward all HTTP requests (port 80) to my computer. This is how my setup looks like -

image

  • That’s it, all incoming HTTP requests will be forwarded to your computer now. However, we’re not done yet – these incoming requests will be blocked by your computer’s firewall. We need to open port 80 on the firewall as well.
  • Open Windows Firewall configuration - If you are on Windows 7, go to Control Panel->System & Security->Windows Firewall. From the left hand menu, choose “Allow a program or feature through Windows firewall”.

image

  • In the list of services that comes up, go to the last one (World Wide Web Services (HTTP)), and check both the private and public checkboxes.

image

  • Now we’re done – your web service is now callable from the internet.
  • To test this, visit http://www.webpagetest.org/, and put your web service URL. Your web service URL is - http://{your ip address}/MyWebService/Service1.asmx. For e.g., my web service IP address is - http://75.123.65.169/MyWebService/Service1.asmx.
  • So there you go, your web service should now be accessible from the internet. It is also now ready to be called by Salesforce. In my next post, we will go over the basics of calling this web service from Salesforce.com.

Calling External Web Services from Salesforce.com Part I: Hosting your web service

Part I: Hosting your web service
Part II: Opening your web service to the internet
Part III: Building an Apex class that calls your web service

The other day, I read about the ability to call external web services from Salesforce.com, and decided to give it a try. I come from a Microsoft programming background, so I expected it to be simple & straightforward. I ended up jumping through hoops, and by the end of it, I had already decided to write this post to save others the trouble.

I decided to break the whole process down into four parts -
Part 1 – will focus on how to build the webservice that we will be using.
Part 2 – will focus on how to make the webservice accessible to Salesforce.com from the Internet.
Part 3 – will focus on the Apex code etc. required on the Salesforce side to call the web service.
Part 4 – will focus on advanced issues like error handling, arrays etc.

In this part, we will simply build an old-fashioned asp.net web service. Since this is a fairly routine task for any programmer worth his salt, I will keep the instructions as concise as I can. So, here goes:-

  • Launch Visual Studio – I am using Visual Studio 2008. Create a new Asp.Net web service (File->New->Project->Visual C#->Asp.Net Web Service Application). Name it “MyWebService”, and hit Ok.

image 

  • Hitting Ok should automatically generate a basic asp.net web service. In the solution explorer (View->Solution Explorer), there should already by a web service file named [Service1.asmx], and the corresponding C# code file [Service1.asmx.cs].
  • Hit F5, or go to Debug->Start Debugging from the menu to execute the web service. It should show you a page like the one below -

image

  • Next, you need to make sure that IIS is running on your machine. You can go to Start->{Type IIS in the search box}. This should launch IIS on your machine. If you don’t have it installed, you can visit this link to see how to install IIS.
  • Navigate to the IIS root folder- this is usually C:\inetpub\wwwroot. Create a new directory called “MyWebService” here. You will need administrative privileges on the machine for this.

image

  • Next, we are going to “Publish” the web service. Publishing is the process where the web service is actually “hosted” on IIS, instead of within visual studio.
  • In Solution Explorer, right-click on the project name, and select “Publish…”. In the “Publish Web” dialog box that comes up, click the ellipsis next to “Target location”, and navigate to the folder we just created.

image 
image

  • Make sure that you select the option “All project files” in the “Copy” section on the dialog box. and click “Publish”.
  • Once the publish is done, try navigating to http://localhost/MyWebService/Service1.asmx. If everything is setup correctly, this should bring up the web service page.

That wraps up our first part – creating a bare bones web service. In the next post, we will see how to expose this web service to the internet so that Salesforce.com can call it.

Tuesday, May 28, 2013

Salesforce.com and Web Service Integration

Get Response From External Website

1. Apex Class TestPing with DoPing() method

Using Ping instead of CreateandSendPackage for brevity – Just replace SOAPXMLBody string with the above and change your Username, Password and AccountID with yours.  You will need to break out over several string concatenations aka

SOAPXMLBody = SOAPXMLBody + "big long string";

2.  Immediate execution code from Salesforce System log or Eclipse

SalesForce System Log Debug Output


Debug output should look like:

3.  Final WSDL for Ping and CreateandSendPackage

Thursday, May 23, 2013

Calling a REST Web Service (JSON) with Apex

Calling a REST Web Service (JSON) with Apex

Using JSON RESTful Web Services with Salesforce.com opens up your org to a number third-party integration opportunities (Google, Yahoo!, Flickr, bespoke, etc.). JSON support isn't baked into the Force.com platform but Ron Hess at Salesforce.com has created a JSON parser which will do the heavy lifting for you.

Last month I wrote a blog post and example of how to call a REST Web Service with Apex that returns and consumes XML. It was my intention to do the same demo using JSON, however, I ran into a small sang. I couldn’t get the Apex JSONObject parser to work. I tried on and off for a couple of days but couldn't beat it into submission. I checked around the twitter-verse and no one reported much success using the JSON parser with complex objects. I finally cried "uncle" and called Ron and asked for help. Ron was extremely responsive and over the course of a couple of days we worked worked through some of the parsing issues and finally updated the Google project with the changes.

I put together a small demo where you enter your address and the Apex code fetches the address and coordinates from the Google Maps . The service returns the data as a JSON object. You can run this example on my Developer Site.

To get started, you'll need to download the JSONObject class and install it into a Developer org or Sandbox. Unfortunately there is no documentation for the parser so you have to extrapolate from the json.org website.

You'll also need to sign up for a Google Maps API key in order to use their geocoding service. I would also recommend that you take a look at the docs for Google Maps geocoding service.

Here is the Controller for the demo. The interesting stuff is in the getAddress() and toGeoResult() methods. In getAddress(), the user-entered address is used to construct the URL for the GET call to the geocoding service. Make sure you properly encode the address or you may receive undesirable results returned from Google. One thing to point out is line #58. Google is returning a line feed in their JSON response which causes the JSON parser to choke. I simply replace all like feeds with spaces and that did the trick. Ron was going to look into making this change to the JSONObject class in the near future.

I was also having some problems with the geocoding service so I hard-coded the returned JSON object for testing. I checked around and it seems to be a common problem that the Google Maps API randomly returns 620 errors when overloaded. You might want to take a look at the JSON response returned for the hard-coded address. I will give you a little insight for the parsing process.

The toGeoResult() method parses the returned JSON response and populates the GeoResult object with the appropriate data. I chose this Google Maps example because it shows how to parse simple values, nested JSON objects and arrays. The coordinates for the address can either be returned as integers or doubles so I have to check each one.


The Visualforce page is fairly simple and presents the user with a form to enter their address. If the geocoding services is experiencing issues, the user can check "Use hard-coded Google JSON response?" and the Controller with use the hard-coded JSON response instead of making the GET call to the geocoding service. Once submitted, the address is processed and the outputPanel is rerendered with the resulting address and coordinates.



Labels

visualforce page ( 13 ) apex integration ( 5 ) apex trigger ( 4 ) csv file from vf page ( 4 ) javascript ( 4 ) csv visualforce page ( 3 ) Too many ( 2 ) call out ( 2 ) integration ( 2 ) rest api ( 2 ) salesforce rest api ( 2 ) salesforce to salesforce integration ( 2 ) sfdc rest api ( 2 ) trigger ( 2 ) 15 digit to 18 digit ( 1 ) DML rows in Apex ( 1 ) Date Conversion ( 1 ) Date/Time conversion ( 1 ) Deploy ( 1 ) Objects to Future Annotated Methods ( 1 ) SFDC limits ( 1 ) Sobject to Future Annotated Methods ( 1 ) Test Class ( 1 ) TimeZone Conversion ( 1 ) Too many dml rows ( 1 ) Too many future calls ( 1 ) annotations ( 1 ) apex code ( 1 ) closed opportunities ( 1 ) commit ( 1 ) convert ( 1 ) create records ( 1 ) csv create records ( 1 ) custom setting ( 1 ) deployment ( 1 ) deployment changeset ( 1 ) disable apex class ( 1 ) disable apex trigger ( 1 ) disable in production ( 1 ) document ( 1 ) download ( 1 ) field name ( 1 ) formula fields ( 1 ) iframe ( 1 ) inactive ( 1 ) intellisense ( 1 ) jsforce ( 1 ) limits ( 1 ) matrix report in vf page ( 1 ) multi select ( 1 ) multi select salesforce ( 1 ) multiselect ( 1 ) paypal ( 1 ) picklist ( 1 ) record type ( 1 ) rollback ( 1 ) salesforce limits ( 1 ) salesforce list ( 1 ) salesforce map ( 1 ) salesforce rest ( 1 ) salesforce set ( 1 ) salesforce1 ( 1 ) sandbox deployment ( 1 ) sfdc collection ( 1 ) sfdc list ( 1 ) sfdc map ( 1 ) sfdc rest ( 1 ) sfdc set ( 1 ) uncommitted ( 1 ) updated field ( 1 ) user ( 1 ) validation rule opportunity ( 1 ) validation rules opportunities ( 1 ) vf page ( 1 )

Ad