Parsing JSON in Salesforce Apex is an important part of salesforce development and is used to integrate data into Salesforce. In this post, we will learn how to parse JSON in Apex to consume external API data in Salesforce.
JSON (JavaScript Object Notation) is a text-based data interchange format that is used to transmit, transport and store data. It is commonly used to exchange data between web applications, client and server endpoints, database systems and more.
The best way to parse JSON data
Let’s see an example:
public class MyClass {
public String field1;
public String field1;
public static MyClass parse(String json) {
return (MyClass) System.JSON.deserialize(json, MyClass.class);
}
}
When it comes to Salesforce development, there are various tools and techniques that can help make the development process more efficient. One such technique is using an Apex method to get the ISO code by country name. By using an Apex method, you can quickly and easily obtain the required ISO code based on the country name.
An ISO code is an international standard used to identify a specific country, region, province, or language. For example, each country in the world is assigned a unique ISO code, such as the United States (USA
Salesforce Apex provides developers with the ability to retrieve ISO Code information for specific countries. This is useful for international applications where a user’s country or language needs to be stored. To prevent confusion, ISO Codes are often used in such cases.
There are several ways to create an Apex method to retrieve an ISO Code. Let’s see one of them.
If you want to get the ISO code by country name, see this post
public static String getIsoCodeByCountryName(String countryName) {
if (countryName == null) return null;
Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> pickListValues = fieldResult.getPicklistValues();
for (Schema.PicklistEntry pickListEntry : pickListValues) {
// pickListEntry.getLabel() returns the country name
// pickListEntry.getValue() returns the country code
if (pickListEntry.getLabel().toLowerCase() == countryName.toLowerCase()) {
return pickListEntry.getValue();
}
}
return null;
}
How to test the Apex method getIsoCodeByCountryName
@isTest static void testGetIsoCodeByCountryNameDynamic() {
// given
List<String> countries = getCountries();
for(String country :countries){
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode != null);
}
}
@isTest static void testGetIsoCodeByCountryNameInvalid() {
// given
String country = 'invalid country';
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode == null);
}
@isTest static void testGetIsoCodeByCountryNameNull() {
// given
String country = null;
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode == null);
}
See that one of our test cases uses one aux method called getCountries to get all the countries available in the your Salesforce instance
public static List<String> getCountries(){
Schema.sObjectType objType = Contact.getSObjectType();
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
list<Schema.PicklistEntry> values = fieldMap.get('MailingCountryCode').getDescribe().getPickListValues();
List<String> countries = new List<String>();
for (Schema.PicklistEntry v : values){
countries.add(v.getLabel());
}
return countries;
}
Technical debt is a concept in software development that refers to the extra work that is created when a programmer takes a shortcut or a less-than-ideal approach to code design. It is the cost of future rework caused by decisions made in the present when a technology solution is built.
Technical debt manifests itself in many ways, but generally represents the cost of knowingly making decisions in your codebase that you may regret later.
Technical debt is a term that has become increasingly important in the software development industry. It refers to the cost of maintaining or improving a software system that arises from taking shortcuts or making compromises during the development process. In this blog post, we will explore the concept of technical debt, its types, and its consequences, as well as ways to manage and minimize it.
What is Technical Debt?
Technical debt is a metaphor used to describe the cost of shortcuts or compromises made during the development process. These shortcuts or compromises are typically taken in order to meet deadlines or deliver products quickly, but they can result in long-term costs for the project. Just like financial debt, technical debt accumulates over time and must be repaid with interest. The longer it goes unpaid, the more costly it becomes.
There are several types of technical debt, including:
Code debt: This occurs when code is written in a way that is not optimal, which can make it harder to maintain, debug, or modify in the future.
Design debt: This occurs when the design of a software system is not properly planned or documented, which can lead to poor performance or scalability. Probably the hardest and the most expensive one.
Testing debt: This occurs when testing is not done properly, which can lead to undetected bugs or security vulnerabilities. This is the most boring to pay so make sure your write good tests at the same time you write the code base. I know, it takes more than 50% of the work but it worth.
Documentation debt: This occurs when documentation is not done properly, which can lead to misunderstandings or confusion about the software system. <sarcasm>We like to write documents!</sarcasm>
The Consequences of Technical Debt
The consequences of technical debt can be significant, and they can impact various aspects of the development process, such as the quality of the software, the productivity of the development team, and the overall cost of the project. Some of the consequences of technical debt include:
Increased maintenance costs: As technical debt accumulates, it becomes more costly to maintain and improve the software system.
Decreased software quality: Technical debt can lead to a decrease in the quality of the software, as bugs and other issues can go undetected or unresolved.
Increased development time: As technical debt accumulates, it can become more difficult to make changes or add new features to the software, which can increase the development time.
Decreased team productivity: Technical debt can lead to decreased team productivity, as developers may spend more time maintaining the software instead of working on new features.
Managing Technical Debt
Managing technical debt is essential to ensure the long-term success of a software project. There are several ways to manage technical debt, including:
Identifying technical debt: The first step in managing technical debt is to identify it. This can be done through code reviews, testing, and other forms of analysis. You don’t need a deep analysis, all we know in the team which part of the code must be improved
Prioritizing technical debt: Once technical debt has been identified, it is important to prioritize it based on its impact on the software system.
Paying off technical debt: Paying off technical debt involves taking steps to improve the software system, such as refactoring code, improving testing, or updating documentation.
Preventing technical debt: Preventing technical debt involves taking steps to avoid it in the first place, such as setting realistic deadlines, planning the software design, and prioritizing testing and documentation.
In conclusion, technical debt is a significant issue in software development that can have long-term consequences for the quality, productivity, and cost of a project. By identifying, prioritizing, paying off, and preventing technical debt, developers can ensure that their software systems are stable, maintainable, and effective.
Handlebars is a popular templating library that can be used to generate dynamic HTML pages. You can use Handlebars in an AWS Lambda function by following these steps:
Create an AWS Lambda function: To start, you need to create an AWS Lambda function in which you will write your code.
Install Handlebars: To use Handlebars in your Lambda function, you need to install it as a dependency. You can do this by adding handlebars to the dependencies section of your project’s package.json file and running npm install.
Load the Handlebars library: In your Lambda function code, you need to load the Handlebars library. You can do this by including the following code:
const handlebars = require('handlebars');
Compile a Handlebars template: To use Handlebars, you first need to compile a Handlebars template that specifies the structure of your HTML page. You can do this by using the following code:
Render the template: To render the template, you need to pass in an object that provides the values for the template’s variables. You can do this by using the following code:
const html = template({ name: 'AWS Lambda' });
Return the generated HTML: Finally, you need to return the generated HTML from your Lambda function. You can do this by including the following code:
Deploy the function: After you have written your code, you need to deploy your Lambda function to AWS. You can do this using the AWS CLI or the AWS Management Console.
These are the basic steps for using Handlebars in an AWS Lambda function. You can customize this code to meet the specific needs of your application.
You can get the Visualforce usage statistics from the VisualforceAccessMetrics object in Salesforce by using SOQL (Salesforce Object Query Language) to query the object and retrieve the desired information. Here’s an example of how you can do this:
SELECT ApexPageId, MetricsDate, TotalTime, AverageTime, TotalRequests, UniqueUsers
FROM VisualforceAccessMetrics
WHERE MetricsDate = TODAY
This query retrieves the Visualforce page ID, date, total time, average time, total requests, and unique users for the current day. You can modify the query to retrieve data for a different time period by changing the value in the WHERE clause.
Once you have executed the query, you can use the results to get the desired statistics and usage information for your Visualforce pages.
As a Salesforce administrator or developer, you may need to download a ContentVersion file through the Salesforce REST API using Curl. In this post, we’ll show you how to download the file with Curl in a few simple steps.
First, you’ll need to execute a query and extract the Content Version File ID. To do this, you can use Workbench or the REST explorer and issue a query like this:
SELECT Id, VersionData
FROM ContentVersion
WHERE Title = 'titleOfFile'
Or
SELECT Title, VersionData
FROM ContentVersion
WHERE Id = '0684V00000Qhf3mABB'
To download a ContentVersion file in Salesforce through the REST API, you’ll need to make a GET request to this endpoint:
Where <strong>XX</strong> is the Salesforce API version you’re using (e.g. 56 for API version 56), and recordId is the unique identifier of the ContentVersion record you want to retrieve.
Note that you’ll need to replace the following placeholder values:
<ACCESS_TOKEN>: with a valid Salesforce access token.
<instance>: with your Salesforce instance name (e.g. na1, eu0, etc.).
XX: with the Salesforce API version you’re using.
{recordId}: with the unique identifier of the ContentVersion record you want to retrieve.
Also, note that you’ll need to set the Content-Type header to application/octet-stream to indicate that you’re downloading a binary file.
In the response, the binary data of the ContentVersion file will be included in the body. You can write this data to a file on your local machine to save it.
The event loop is a fundamental concept in Node.js, and is responsible for executing the JavaScript code in a non-blocking, asynchronous manner.
In Node.js, all I/O operations are performed asynchronously, which means that they don’t block the execution of the main thread. Instead, these I/O operations are registered with the event loop, and the event loop will call the callback function when the I/O operation is complete
This allows the program to continue executing other code while waiting for the I/O operation to complete.
The event loop in Node.js consists of several phases, including the timers phase, the pending callbacks phase, the idle, prepare phase, and the poll phase. In each phase, the event loop will process a different set of tasks. For example, in the timers phase, it will process timers that have expired, and in the poll phase, it will process I/O events.
It’s important to note that the event loop is a single-threaded loop, which means that only one task can be processed at a time. However, due to the non-blocking nature of Node.js, the event loop can efficiently handle multiple I/O operations in parallel, which gives the illusion of multithreading.
In summary, the event loop in Node.js is the mechanism that enables the program to execute JavaScript code in a non-blocking, asynchronous manner, by processing I/O operations as events and calling the corresponding callback functions when the I/O operations are complete.
Organic traffic can be a challenge to increase, however, with consistency and dedication, it is possible to drive more visitors to your blog. Here are 5 ideas to help increase the organic traffic to your blog. But before we start, unfortunately there’s not a secret sauce, it requires effort and dedication to analyze our stats and tweak our techniques.
Here are five actionable ways to increase organic traffic to your blog
1 – Create Quality Content
Content is essential to organic traffic growth. If your content is well researched, well written, and keyword-rich, then it will be more likely to drive traffic to your blog. Quality content will also help establish your blog as a reliable source of information which will keep readers coming back for more.
Write blog posts that are informative, engaging, and provide value to your target audience. Make sure to regularly update your blog with new and fresh content to keep your visitors coming back.
Not inspired? Take a look at Google trends to explore what the world is searching.
Speaking of content, do not try to cheat on users and search engines. Sooner or later they will realize and will leave your site and release your hand over time so write native content.
The content and its value is the most important thing you can do to get traffic.
2 – Optimize for search engines
Make sure your blog posts are optimized for search engines by using relevant keywords, meta descriptions, and header tags. This will help your blog rank higher in search engine results and attract more organic traffic.
Optimize your blog for organic search by identifying targeted keywords and using them in titles, headings, and through each article. Organic traffic it’s one of the most important because it means that a search engine suggested our site for users.
Clear HTML to make search engine life easier to read our content. Use meta tags in the right way. Use structured data.
3 – Do Networking
Reach out to other bloggers in your niche and offer to guest post on their blog. This will give you access to a new audience and help you build relationships with other bloggers in your industry. Comment on other related blog posts and join online communities to create a network of followers and readers.
Build backlinks. Encourage other websites to link back to your blog. The more backlinks you have, the higher your blog will rank in search engine results, and the more organic traffic you will receive.
Use email marketing to reach out to potential readers and invite them to follow your blog.
Utilize social media to share your blog posts on social media platforms such as Facebook, Twitter, and LinkedIn to engage with potential readers. This will help drive more traffic to your blog and increase your visibility online.
4 – Monitor analytics
There are several tools to analyze how your content is doing. Here are some of them I use:
Google Analytics. Probably the most used.
Google search console. It’s super useful to get good insights.
Jetpack. In case you use WordPress, Jetpack stats are pretty straightforward to understand and super useful
Social media analytics. Some of them offer you analytics to know the content that works well.
Regardless of the tool your use, take a look at:
Keywords that bring you more content and work on those that don’t but you think are related to what you write.
Pages with the most page views to analyze why users like it.
Pages that you think that add value but still users or search engines don’t read. For these cases you may consider rewriting it, optimizing images, ads, etc. Maybe the content is good but it is not well organized and easy to read.
See where users come from such as social media, organic, etc.
If you invested money in campaigns, take a look at if it really brought up traffic by analyzing referrals.
5 – Optimize page loading
Optimizing page loading speed is crucial for the user experience of your blog, as well as for your search engine rankings. Let’s see some tips to help you optimize your blog for faster page loading.
Compress images: Large image files can significantly slow down your page loading speed. Use an image compression tool to reduce the size of your images without sacrificing quality. There are also external services such as Cloudinary to serve your images super optimized.
Minimize HTTP requests: Every time a page loads, it makes multiple HTTP requests to fetch various components like images, scripts, and stylesheets. Minimizing the number of requests can help speed up the page loading time.
Use a Content Delivery Network (CDN): A CDN can help distribute your content across multiple servers, reducing the load on your main server and speeding up page loading time for users in different locations.
Minify CSS, JavaScript, and HTML: Minifying your code means removing all unnecessary characters, such as whitespace and comments, which can help reduce file size and improve page loading time.
Enable browser caching: Browser caching allows your pages to load faster for returning visitors by storing static content, such as images and stylesheets, in the visitor’s browser cache.
Use asynchronous loading for JavaScript: Loading JavaScript synchronously can block the rendering of the page, leading to slower page loading times. Using asynchronous loading allows the page to continue loading while the JavaScript is being loaded in the background.
Choose a good hosting provider: A reliable hosting provider with fast server response times can have a significant impact on your page loading speed.
Avoid loading your blog with a lot of advertising.
Avoid annoying popups asking for email subscriptions or any other alert messages.
By following these tips, you can significantly improve the page loading speed of your blog, providing a better user experience for your visitors and helping to improve your search engine rankings.
Pro tip: with PageSpeed Insights tool you may have excellent information, see https://pagespeed.web.dev/
Conclusion
Implementing these strategies will take time and effort, but they can significantly increase the organic traffic to your blog over time. This only can be achieved if our content adds value but also if it loads fast and it is well indexed.
In Salesforce, you can query accounts with at least one closed won opportunity by using a SOQL (Salesforce Object Query Language) query. Here’s an example of how you could write this query:
SELECT Id, Name, (SELECT Id, Name, StageName
FROM Opportunities
WHERE StageName='Closed Won')
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity
WHERE StageName='Closed Won')
LIMIT 10
This query returns all accounts that have at least one opportunity in the “Closed Won” stage. The inner query (SELECT Id, Name, StageName FROM Opportunities WHERE StageName='Closed Won') retrieves the closed won opportunities associated with each account, and the outer query (SELECT Id, Name, (...) FROM Account WHERE Id IN (...)) retrieves the account information for accounts with at least one closed won opportunity.
You can use this query in a number of different ways, such as in the Salesforce Developer Console, in Apex code, or in a tool such as the Workbench. Once you have the results, you can use them for further analysis, reporting, or to perform additional actions.