Weather Underground Integration with Salesforce

Recently at Cloudjedi, we did a Weather Underground integration with Salesforce to regularly forecast temperatures for every city to enable our customer to predict demand for their popsicle business. The idea was to query Weather Underground API using a scheduled Apex batch and save the temperature forecast to the database pertaining to each city.  

You can browse the Weather Underground API from their website. But here's a developer guide on how we did the Weather Underground integration.

The Salesforce schema contained a Climate custom object. Each Climate object pertains to a city, and saves the weather forecast for the next 10 days.

 

1. Create a new Climate object and save the correct Weather Underground query string in the Climate record. Use an object field Weather_Underground_Query__c to save this query string. The following is an example of a well-formed HTTP request that queries Weather Underground for the weather condition of today and the next nine days:

http://api.wunderground.com/api/<API_Key>/forecast10day/q/CA/San_Francisco.json

The query string can come in many formats:

- StateName/CityName - CountryName/CityName - CityName - CountryISOCode/CityName

The desired response format should be appended at the end: “.json” is what we used. The Weather Underground API also provides unique city codes that can be used for querying. For example, to query a forecast for New York, the HTTP request should include the New York zmw code "zmw:31003.1.99999":

http://api.wunderground.com/api/<API_Key>/forecast/q/zmw:31003.1.99999.json

Ambigous queries return an array of possible cities from which the correct query can be selected. If a city is ambiguous, manually make sure that the query works before running the Apex job. For example if "Argentina/BuenosAires.json" doesn’t return the correct JSON response, try requesting for "BuenosAires.json" or "AR/BuenosAires" Save the working query in Weather_Underground_Query__c

 

2. Create an API class that interacts with Weather Underground and parses the HTTP Response data. We named it WundergroundAPI. It has the following methods:

public static WundergroundAPI callout(String path){
  HttpRequest req = new HttpRequest();
  req.setEndpoint('http://api.wunderground.com/api/' + wundergroundAPIKey + path);
  req.setMethod('GET');
  Http http = new Http();
  HttpResponse res = new HttpResponse();
  res = http.send(req);
  return WundergroundAPI.parse(res.getBody());
}
 

Since we used JSON, one of the benefits is that we can easily generate using JSON2Apex the corresponding Apex class components needed to parse the response using System.JSON.deserialize().

public static WundergroundAPI parse(String jsonString) {
  return (WundergroundAPI) System.JSON.deserialize(jsonString, WundergroundAPI.class); }

 

3. Create a Schedulable Batchable Apex class that schedules its own batch job daily.

In implementing the execute method of the Batchable interface, use the WundergroundAPI.callout() method to generate a response class. In this case the JSON2Apex deserialization created a WundergroundAPI object that has the JSON data in its attributes. Use this WundergroundAPI object to navigate through the response class properties to get the max temperatures for each day of the forecast period.

public void execute(Database.BatchableContext BC, List<Climates__c> climates){
  for (Climate__c climate : climates) {
    String cityAPICode = clima.Weather_Underground_Query__c;
    String fullRequestPath = formatURLPath('forecast10day',cityAPICode);
    WundergroundAPI calloutResponse = WundergroundAPI.callout(fullRequestPath);
    List<WundergroundAPI.Forecastday_Z> forecasts = calloutResponse.forecast.simpleforecast.forecastday;
    climate.TEMP_max_today__c = forecasts[0].high.celsius;
    climate.TEMP_max_tomorrow__c = forecasts[1].high.celsius;
    climate.TEMP_max_in_2_days__c = forecasts[2].high.celsius;
    climate.TEMP_max_in_3_days__c = forecasts[3].high.celsius;
    climate.TEMP_max_in_4_days__c = forecasts[4].high.celsius;
    climate.TEMP_max_in_5_days__c = forecasts[5].high.celsius;
    climate.TEMP_max_in_6_days__c = forecasts[6].high.celsius;
    climate.TEMP_max_in_7_days__c = forecasts[7].high.celsius;
    climate.TEMP_max_in_8_days__c = forecasts[8].high.celsius;
}
private static String formatURLPath(String feature, String query){
  return '/' + feature + '/q/' + query + '.json';
}
 

Do not forget to schedule the execute method for the Schedulable interface. public void execute(SchedulableContext sc){
  String actualQuery = 'SELECT Id, Name, Weather_Underground_Query__c FROM Climate__c)';
  WeatherForecastBatch batch = new WeatherForecastBatch  (actualQuery);
  Database.executeBatch(batch, 200);
}

HP IDOL OnDemand on Salesforce (Apex)

What is IDOL OnDemand?

IDOL OnDemand delivers a growing set of RESTful APIs to help developers build apps that tackle the explosive growth of unstructured data. We’re exposing the capabilities of HP IDOL (Intelligent Data Operating Layer), the world’s leading on-premise human information processing engine, to deliver a wide selection of web services, including sentiment analysis, face detection, entity extraction, text indexing, and more – for quick and lightweight integration into your apps.

This article assumes that you already have an existing Salesforce developer edition account. If you still don't have a developer account, you may signup here:

Here are the steps on how to sign-up to IDOL OnDemand API Key

  1. Signup for an API key via the following link: https://www.idolondemand.com/signup.html
  2. Once finished, you will receive an API Key that looks like the following: xxxxxxxx-xxxx-xxxx-xxxx-10def765b016
  3. Take note of this key as we will use this to modify the Apex Class named IDOLClient.cls to allow you o try out the application using your own key.

Install the IDOL Demo Package

  1. Click on the installation link and then log into your Salesforce instance to install the application
  2. Make sure to grant third party access to "api.idolondemand.com"
  3. Click next on the Step 1. Approve Package API Access
  4. Select "Grant access to all users" on Step 2. Choose security level then hit next
  5. Click "Install" to install the package
  6. After installation, click the following link to get to the page. https://login.salesforce.com/apex/IDOLDemo
  7. If you see any errors on the previous step, make sure to log-out of any other salesforce instance and login to your developer edition account

Start playing with the HP IDOL OnDemand Application

  1. Select the API to test using the dropdown selection provided
  2. The text to search for Wikipedia and URL to search is provided for the convenience of the user upon selection
  3. Click "Execute API" to call the IDOL API and the results will be provided to the user in the text area provided
  4. The package is an Unmanaged Package so you may view all of the contents of the code

Using your own API Key

If you would like to use your own API Key, you may go to YOUR_NAME > Setup > App Setup > Develop > Apex Classes and edit the class named IDOLClient. Replace the value of the API_KEY with your own Key.

 

Salesforce codes included in the application

Apex Classes:

  • IDOLClient.cls - Main wrapper class for the HP IDOL OnDemandAPI
  • IDOLDemoController.cls - Controller for the IDOL Demo allowing the user to test out the API via a VisualForce page
  • IDOLAnalyzeSentimentResponse.cls - Converts the Analyze Sentiment JSON response into an Apex Class
  • IDOLFindSimilarResponse.cls - Converts the Find Similar JSON response into an Apex Class
  • IDOLOcrDocumentResponse.cls - Converts the OCR Document JSON response into an Apex Class
  • IDOLAnalyzeSentimentResponseTest.cls - Unit Test classes for IDOLAnalyzeSentimentResponse.cls
  • IDOLClientTest.cls - Unit Test classes for IDOLClient.cls
  • IDOLDemoControllerTest.cls - Unit Test classes for IDOLDemoController.cls
  • IDOLFindSimilarResponseTest.cls - Unit Test classes for IDOLFindSimilarResponse.cls
  • IDOLOcrDocumentResponseTest.cls - Unit Test classes for IDOLOcrDocumentResponse.cls

VisualForce pages:

  • IDOLDemo.page

 

Tips:

  • If you would like to try out the other API provided, you may use the following link to easily generate Apex Code from JSON response. http://json2apex.herokuapp.com/

 

Common Data Loader Errors

AppExchangeDataLoader
AppExchangeDataLoader

Data Loader helps in mass updating, inserting, upserting, deleting, and exporting your data. It is ideal for any organization that manages more than 50,000 records. As compared to Import Wizard, Data Loader supports more objects and can process more records. However, Data Loader is only available for Enterprise editions and above.

One of the most common cases being submitted to Salesforce.com support pertains to common data loader errors. It is important to be familiarized with these common data loader errors in order to prevent it from impacting your business. For data that require immediate processing, it is pertinent to know the initial steps needed to be done.

Here are some of the common data loader errors:

1. Error: Row is larger than header - this means that there is a data in a field that has no header to be mapped. To resolve the issue, please make sure that your import file has a header, and map it to appropriate field upon doing the import.

2. Error: System.Exception: Too many SOQL queries - the error means that there is a trigger on the object and it is currently exceeding the governor limits. To resolve the issue, you can either modify the trigger or have Salesforce.com support increase your API calls.

3. Error: Duplicate value found - this means that you are attempting to update a unique field. To resolve the issue, please ensure that the field/s you're attempting to update is/are not unique field/s. If they are unique fields, then you must enter a unique or different value. You can also consider temporary removal of a field's uniqueness while doing the update by clicking: Name | Setup | Customize | Object | Field | Click Edit on the field | Un-check "Do not allow duplicate values" | Save

4. Error: Owner ID: ID value of incorrect type - unlike Import Wizard, Data Loader requires Owner ID and not the record name to map the record owner.

5. Error: [INVALID_CROSS_REFERENCE_KEY].Messae [Customer Record Type: id value not valid for the users profile: xxxxxxxxxxxxx] - this error message usually appears when you are the record type being assigned to a user is not yet active on his profile. To resolve the issue, the following steps should be done: Click on Setup | Manage Users | Click on the profile that the record type needs to be added to | Scroll down to the Record Type Settings section | Click Edit on the Object | Select the specific record type in the list "Available Record Types" and add it to "Selected Record Types | Save

These are just one of the most common data loader errors. If you have other error messages to report, please feel free to comment on this website or contact us at info@cloudjedi.com.

COMMON APEX CODE ERROR MESSAGES

Although the standard Salesforce features are helpful and efficient, it is sometimes required for you to create custom Apex codes in order to improve system performance and triggers that are currently not possible with your standard Salesforce functionality. In order to avoid  apex code error messages that could potentially impact your business, it is pertinent for you to be familiarized with these common errors and get to know how to resolve them. REQUEST_LIMIT_EXCEEDED

This is one of the most common Apex code error messages, and it often appears when your API call limit for your organization has been already exceeded due to huge number of integration with third party applications.

When integrating with third party applications, it is important to consider how would these applications affect your API call limit. It is important to plan and evaluate how these applications would be used in order to prevent the limit from being exceeded.

The best way to monitor API usage is either to run an API usage report or monitor your limit under Setup | Administration Setup | Company Profile | Company Information.

FIELD_CUSTOM_VALIDATION_EXCEPTION

Validation Rules are helpful, but could also be painful, if not correctly used or deployed. In order to avoid this error, Validation Rule should be created based on your business needs, and make sure that it would not conflict with other triggers or rules. Rules should also be assessed periodically to make sure that they are still needed in the organization, if these rules are deemed unnecessary for the org, then the rules could be modified or deleted already.

One of the best ways to deal with this error is to make the class calls a DML operation, specially when deploying a batch class. The opt_allOrNone shouls also be set to False. This workaround would allow saving of the record even though it fails to meet the Validation Rule/s.

STRING_TOO_LONG

This error usually occurs when the length of the entered text is longer than the field length limit. The field length can be modified by going to Name | Setup | Customize | Object Name | Field | Click Edit on the field being modified | Change the length | Save.

 

Improving your Apex codes and modifying your current customization are necessary to properly deploy Apex codes and avoid encountering errors. If you would like to know more about custom Apex code creation and integration, you may contact us for assistance at info@cloudjedi.com.

Salesforce Spring 14 is Coming!

Spring14Logo2
Spring14Logo2

In order to provide customer satisfaction, Salesforce continuously provide quarterly releases in order to introduce new features and functionality depending on the needs and demands of their customers. Spring 14 release is scheduled to start on February 7, 2014. In order to maximize the new features and to prevent potential data issues, it is important to be prepared and familiarized with the latest Salesforce release.

Sandbox Preview

If you have refreshed your Sandbox before January 3, 2014, then you would have the chance to maximize the Sandbox Preview instance in order for you to test new Salesforce features. It would also prevent your organization from potential data loss. Moreover, this will aid in familiarizing yourself with the latest features without the worry of having your records and customization affected.

To know more about the Sandbox Preview instruction, please refer to this link: http://blogs.salesforce.com/company/2013/11/spring-14-sandbox-preview-instructions.html.

Plan Accordingly

It is the time to determine how the end users would be trained regarding the newest features. You may also need to figure out which of the new features would give more benefits to your organization. You may also need to export your records in order to prevent potential record deletion upon rolling out the latest release. You could also consider reading the release notes at https://help.salesforce.com/help/pdfs/en/salesforce_spring14_release_notes.pdf in order to prevent worries if ever you would see some changes on your Salesforce account.

Highlights of the Release

Here are some of the features that would be introduced on Salesforce's Spring 14 release:

1. Skills and Endorsements (Pilot) – Skills reference data (ProfileSkill) can now be added and associated with People (ProfileSkillUser). Chatter profile will display the skills profile of the user. These skills can also be "endorsed" by other users. Chatter and Setup Pages are the places where the skills can be managed.

2. Feed-Based Page Layouts – This feature would provide convenience and efficiency as it makes Case Feed available also for Account, Contact, Opportunity, Lead, and Custom Objects.

3. API Limit App Quotas (Pilot) - Standard, bulk, and streaming API consumption now have 24 hour API quotas for Connected Apps.

4. Force.com Canvas apps can now be placed into the Salesforce1 navigation menu.

5. Spring 14 also introduces a useful administrator feature that would let you view and manage user sessions.

6. Permission Sets can now be massively assigned.

7. Sharing Sets Enhancements (Pilots) - this would allow indirect lookups from one object to another. This would allow you to access second level of related records.

8. A New User Interface is also introduced to allow you to view and cancel running deployments.

The Future of Salesforce

As Salesforce continuously improve their features, it is no doubt that it would be the next leading CRM tool in the future. Managing your database would be easier as it adapts to the changes and releases. It is always best to be updated with the current trends in order for you to maximize your business and to closely interact with your employees, clients, and customers.

To know more about Spring 14 release, you may check these links:

Spring 14 release video - http://www.salesforce.com/newfeatures/

Spring 14 release notes - https://help.salesforce.com/help/pdfs/en/salesforce_spring14_release_notes.pdf

Major Release Schedule - https://trust.salesforce.com/trust/maintenance/

If you need assistance with preparing your organization for the Spring 14 release, please feel free to contact us at info@cloudjedi.com.

Single Email Limit

SINGLE_EMAIL_LIMIT_EXCEEDED If you've reached this page because you've encountered one of the governor limits imposed by Salesforce, this post will describe some of the reasons why you've reached the limit. One reason why we have this limit is because Salesforce wants to avoid having users use Salesforce as a marketing tool. If you try to ask Salesforce.com Support to increase the limit, they can only do so temporarily.

What COUNTS towards the limit

  • Mass Emails to Contacts
  • Mass Email to Leads
  • Emails send via the API to email addresses
  • Emails send via the API to contacts (Both single and mass emails)
  • Emails send via API to Leads (both Single & Mass Emails)

What DOES NOT COUNT towards the limit

  • Mass emails to Users
  • Emails via API to User ID’s
  • Emails send from the “Send Email” button on contacts (single emails/email author)
  • Emails send from the “Send Email” button on Leads (single emails/email author)

The TO and CC will both count if the recipients are external email addresses. If you send a mass email to 1,000 external recipients, that will use up the email limit in the same way as 100 emails to 10 external recipients.

Mass emails also have limits on the number of recipients you can specify through one mass email call:

  • Professional = 250
  • Enterprise = 500
  • Unlimited = 1000

Also, emails sent with workflow triggers to not count against your email limit, even if sent to a contact or lead. The drawback is that the workflow-generated emails do not create activities associated with the recipient. Also, this is monitored somewhat. If "abused" (and abused is undefined), you could get a response from salesforce.com.

The other BIG problem is that salesforce.com does not expose your daily count of emails. You just a message that you exceeded the limit at some point. If the count were exposed, you would know when to stop.

Source: Bob Buzzard from the DeveloperForce forum and David Claiborne from the Salesforce.com Certified Professionals LinkedIn Group

Multi-Currency Converter Component

If you use multi-currency in your Salesforce instance and need a specific amount shown in your email templates, you may create a Salesforce Component to do the job.

public class currencyComponentController {
    public String RecordId{get; set;}
    public String ObjectName{get;set;}
    public String FieldName{get;set;}
    public Decimal getConvertedAmount() {
        try{
            SObject obj = Database.query('Select convertCurrency(' + FieldName + ') From ' + objectName + ' Where Id='' + RecordId +'' Limit 1');
            return (Decimal)obj.get('Total_Amount__c');
        }catch(Exception e){
            return 0;
        }

    }
}

    
    
    

    

Getting day of the week in Apex

One of the most common function available in other languages for date variables is the one for getting the date of the week. Unfortunately Apex as of version 26 doesn't have it natively. One easy way to get the day of the week is by first converting a date into a datetime variable and then using the DateTime format to get the equivalent date.

Date mydate = Date.newInstance(2012,11,1);
Datetime dt = DateTime.newInstance(mydate, Time.newInstance(0, 0, 0, 0));
String dayOfWeek=dt.format('EEEE');
System.debug('Day : ' + dayOfWeek);

Output:

Day : Thursday

Visit the SimpleDateFormat Documentation to learn more about the DateTime.format function

Dreamforce 2012 - Breakout Session Videos

Dreamforce 2012 has been a great place to learn, interact and meet new people within the Salesforce community. One of its highlights is the hundreds of breakout sessions available from developers to end users. Three days is definitely not enough to go through each of the sessions so if you have any sessions that you still want to learn more about, you may now enjoy them at the comfort of your own home courtesy of Salesforce and Youtube!