March 7, 2016
by Jaswinder Rattanpal
0 comments

Salesforce Trailhead: The fun way to learn salseforce

Are you new to salesforce? Or maybe you have only worked on one area and want to learn about another?

I started on developer side of salesforce. Recently, I figured that if I know about others areas (admin, App Cloud etc) then it will make it so much easier to work on developer side. But I had the same questions as above. Where do I start?

Then I found salesforce trailhead and absolutely love it. It’s not just the content but the way it has been arranged. It took me from beginner admin to intermediate admin and other areas. After I had been through those modules, I wanted to put it all together but couldn’t figure out what I could build.

Lo and behold, trailhead has projects. These are simple enough but still allow me to combine various features that I learned.

My goal now? Go through ALL modules and projects on trailhead to get, at least, basic understanding of all salesforce features. Let the journey start……..

March 8, 2015
by Jaswinder Rattanpal
0 comments

Apex: Find Object Type from Record ID Prefix

I get to work on objects in various orgs. It’s not easy (if at all possible) to remember entity type by just looking at Record ID Prefix. salesforce.com provides a Standard Record ID Prefix Decoder list. This still means you need to have this page handy to find those objects. Of course this list also cannot help with custom objects.

In my pursuit to find an answer, I came across piece of code that was answer to this exact problem. The answer uses iteration on metadata through Schema.getGlobalDescribe(). As it loops through all sObjects in the map, it will continue to check for prefix that we need to find. Once there, it will return the object name. By no means this is an optimized solution as it goes through loop of all sObjects till it can find the object. But this is better than having to go through other ways to find same information. Of course, if you come across an easier way then please share. 

public class SchemaGlobalDescribe{
    public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix){
        String objectName = '';
        try{
            //Get prefix from record ID
            //This assumes that you have passed at least 3 characters
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
            
            //Get schema information
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
            
            //Loop through all the sObject types returned by Schema
            for(Schema.SObjectType stype : gd.values()){
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
                System.debug('Prefix is ' + prefix);
                
                //Check if the prefix matches with requested prefix
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
                    break;
                }
            }
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
    }
}

Now we can easily use this in developer console to check object name whenever we want. Of course you can take it a step further and create a visualforce page, add a search box and make it available to all developers in your org so they can easily use it (if needed).

String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');
System.debug(objectName);

Oh wait, we have written the class, we have tested it but we are missing an important step. Remember? Yes, “Code Coverage”. That’s an important point that we shouldn’t miss. This is important not just to be able deploy the code but it’s good development practice to make sure we test our code. Following salesforce page provides information on testing best practices.

So, I have written very basic test class to cover the code written above. You can add more functionality to your class and then expand on these basic tests.

@isTest
private class SchemaGlobalDescribeTests{
    @istest
    private static void testMethodPositive(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');
        System.assertEquals(objectName,'Case');
    }
    @isTest
    private static void testMethodNegative(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');
        System.assertNotEquals(objectName,'Account');
    }
    @isTest
    private static void testMethodNull(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('101');
        System.assertEquals(objectName,'');
    }
    @isTest
    private static void testMethodException(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('10');
        System.assertEquals(objectName,'');
    }
}

That’s that and now we can easily figure out object name from Record ID prefix.

Please share your thoughts, questions, concerns or constructive criticism. 

 

March 4, 2015
by Jaswinder Rattanpal
3 Comments

Drupal 7: Configure Wysiwyg with TinyMCE

Requirements: Drupal 7

Modules: http://drupal.org/project/wysiwyg

This tutorial will walk you through steps on how to configure wysiwyg editor with TinyMCE. You can, of course, use TinyMCE directly but I like this option as I can use any editor (TinyMCE, TinyMCE, YUI Editor) and can change quickly to another if needed. For that, I will need to download that editor and place it in the libraries folder, configure wysiwyg profile (we will get to it soon) and new editor is ready for use.

Now that we have that out of the way, lets get down to installing and configuring wysiwyg.

Install Wysiwyg modules as per instructions.

Download TinyMCE from http://www.tinymce.com/download/download.php  and unzip it in sites/all/libraries/tinymce folder.

Go to admin/config/content/wysiwyg to configure wysiwyg. I used Full HTML input format for this tutorial because this will ensure that any HTML that we use in content is not filtered; feel free to use Filtered HTML if you want to restrict HTML tags in the content.

You will need to select an editor for this profile. Editor drop down should have ” TinyMCE  n.n” listed. If its not listed then make sure you have properly downloaded  TinyMCE  and unzipped it in sites/all/libraries/tinymce folder (not libraries/tinymce/tinymce)). If you want, you can download multiple versions and select different  TinyMCE  version for each profile (although not sure why you would need to do it but feel free).

Save changes.

This should create a profile for Full HTML with the selected  TinyMCE  version.

Click on Edit in operations column after saving  TinyMCE  version for selected profile. There are many options which are self explanatory. This uorial will only describe minimum setup needed to get this up and running. You can test any options as needed.

Expand “Buttons and Plugins”. This should show all the possible button options that Wysiwyg has to offer that you want to use; I had hoped to select all option in newest version but its not available (yet).

Expand “Cleanup and Output”. I prefer to Uun-check “Remove Line Breaks” option as it allows me to view content easily when viewing in Source Code (or HTML) mode. If this is checked then all code will appear on one line and very hard to read.

Expand “CSS”. Here you can provide path to any CSS file from your theme that you want wysiwyg editor to parse and show styles in “Styles” drop down. I, personally, create a special CSS file for styles that I want to display in styles drop down in wysiwyg editor. This way, I only see styles that I want to use in content rather than all the styles that are used through out the site (for example, menu or sidebar styles).  For this to work, you will need to select “Define CSS” in “Editor CSS” drop down. Now enter “CSS Path” to your style sheet like “%b/sites/all/themes/rattanpal/styles/wysiwyg.css” (%b is the root of your site to ensure it uses absolute to path to avoid any path issues).

That is all we need fo basic configuration of wysiwyg editor in Drupal 7. Its time to save your changes.

If you selected Full HTML like me then you will need to go admin/config/content/formats. Drag full HTML so that its first item in all 3 formats. This will ensure that Full HTML is selected by defauly when you add/edit content.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Drupal 7: Custom Module – Part 2

This is second and last part in Custom Module series. We will use custom module that we created in last tutorial and create a custom front page for a freshly installed Drupal installation

[b]Requirements:[/b] http://www.rattanpal.com/content/drupal-7-custom-module-part-1.aspx

Create a new template called [i]sites/all/theme/page–front.tpl.php[/i]. This template will override the default template and will be used for any page that we decide to use as front page

Edit [i]mymodule.info[/i]. We will ue this file to add custom page. Following code needs to be added to this file. Comments have been added to all code snippets which describe all the items in each function.

/**
* Implements hook_menu()
*
* This will create a URL that we can use to access this page
* This page then can be accessed using http://www.example.com/home
*
* 'page callback': Function to be called to get content when this page is accessed. Output returned by that function is used for "$content" value on that Drupal page
*
* 'access arguments': It adds a key which will be used by Drupal to store ermissions for this page
*
*/
function mymodule_menu() {
$items['home'] = array(
'title' => 'Home',
'page callback' => 'mymodule_home',
'access arguments' => array('access_mymodule_home_page'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_permission().
*
* 'access_mymodule_home_page': Its the same access key defined when 'home' menu item was defined in mymodule_menu()
*
* 'title' & 'description': These will appear on Drupal "Permissions" page to describe what these are for
*/
function mymodule_permission() {
return array(
'access_mymodule_home_page' => array(
'title' => t('Access mymodule Home Page'),
'description' => t('Use mymodule Home Page.'),
),
);
}

/**
* Implement home page
*
* Any string value returned by this function will be used by Drupal for "$content" variable as output of that page
* This can be anything. We could even use it to deliver RSS/JSON/JSONP output if needed
*/
function mymodule_home() {
$content = '';
return $content;
}

 

Clear Drupal cache for Drupal to read new changes to this file.

If you haven’t already then enable this module in admin/modules.

Now go to Site Information (admin/config/system/site-information) and add “home” in “Default front page”. This will ensure that this new custom home page will become our front page and that will also make Drupal use page–front.tpl.php as template

Before your front page can be accessible to anonymous users, you need to give permissions to anonymous users to access this new custom page. To allocate permissions, go to User Permissions (admin/people/permissions). Look for “Access mymodule Home Page” (title of the page). Now check permission box for anonymous user and save permissions.

Voila!. You have just changed your site’s front page to be a custom page. You can add your content directly in page–front.tpl.php or in mymodule_home() function.

This concludes our 2 part series on how to add Custom Module and Custom front page.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Optimize Your Website’s Speed

While working on a website, I noticed that website was not loading as fast as I would like it to. This prompted me to research more on it and find ways to optimize website’s performance. During this research, I came across many useful resources and tools which were very helpful. Following are some of the resources and tools that I’d like to share:

1. Use caching

Most, if not all, websites use databases to store content. This provides unique opportunity to use caching. Caching turns dynamic content into static content so that database is not queried every time a page loaded. These static copies are refreshed in a timely manner or when there is new content. This also alleviates load on web and database servers. For example, Drupal has a core module to not only enable caching but also compressing CSS and JS files (which we will discuss momentarily).

2. Compress JS and CSS

Compressing JS and CSS files is a great way to reduce web page size. CSS size, that I was working on, was reduced from 413KB to 16KB and JS size was reduced from 65K to 16KB; which also included combining all CSS and JS code in two files. There are many tools which can be used to compress CSS and JS. Two of those websites for compressing CSS and JS are http://www.csscompressor.com and http://jscompress.com.

3. Use external JS and CSS

Browsers tend cache resources like JS and CSS while loading a site. If we use CSS and JS files which are hosted on an external site used by many sites then browsers will only need to cache it for one site and re-use cached files for other sites. This technique is getting to be widely used throughout the internet for the benefit it provides. A word of caution, only use content from a trusted source because if it goes offline then it will affect your site even if your site is working as expected.

4. Use Ajax wherever possible

If your website provides content that can be loaded after page has completed loading then try to use Ajax. This can be used in cases like adding content dynamically when page end is reached (similar to Facebook).

5. CSS Sprites

CSS sprite is the method of combining multiple imagse into one image and then using CSS and background positioning these images can be displayed where needed. Using this method, browser will only need to load one image rather than multiple images and then re-use that image for other parts of the site. A good working example of this can be found at http://www.alistapart.com/articles/sprites.

6. Image format

Selecting proper image format when needed can have hue impact on website performance. One of those situations is using jpeg format for photographc images rather than gif format which is suited for text images.

7. Tools for testing speed

There are many online tools that you can (and should) use to test loading time of your website. These tools can point various resources (images, js or css) which ae dding to load time. Use these results wisely and work on a method to reduce load time of those resources. Some of these tools are http://loadimpact.com, http://tools.pingdom.com, http://www.webpagetest.org and http://gtmetrix.com.

Other than above mentioned tips, there are many ways for you to optimize your pages such as sending compressed pages using PHP (http://php.net/manual/en/function.ob-gzhandler.php). As technology evolves, new methods of optimization will be invented. So, keep an eye open for those advancements. I will do my best to research any new techniques and share with you all.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Online Courses

Coursera.com is a great website which provides many courses online for free. These are full fledged courses, generally, provided by professors or professionals in those fields.

The learning tool itself is very clean. It follows a class like structure where you have videos with a theory lesson from instructor followed by a quiz somewhere in that video and an assignment for that week’s lessons.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Machine Learning

Machine Leaning, as described by Coursera, is Learn about the most effective machine learning techniques, and gain practice implementing them and getting them to work for yourself. Just started it today at https://www.coursera.org/course/ml

Really excited about this and am looking forward to next week’s lessons.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Drupal 7: Custom Module – Part 1

When I first started using Drupal, it was simple matter of installing and using it. Then came the task of learning how to theme. But there came a point where required functionality needed to be coded in Drupal rather than just being able to use the GUI interface. One requirement, that started my path towards learning on creating Drupal modules, was custom front-end page and serving ajax pages. I found creating those pages with a custom module easier than some other ideas. But before being able to create a custom page (which wil be discussed in later tutorial) I needed to create a custom module where I could code custom page module. This tutorial will go through steps on how to create a custom module.

A quick note, I will be going through just the basics steps on how to add module. But wherever apppicable, I will be providing links where you can get detailed information. So, think of this tutorial as well explained reference document with information on each resource and not just the reference.

[b]Requirements[/b]: Drupal 7

To start with, we will assume that the name of this module will bemymodule. So, create a folder called mymodule in sites/all/modules folder. We need at least 2 files for a module to work. You can add as many other files as you need to extend your module but these are only 2 required files for a module to work.

First file is to module information like name, description, version etc. This will be used by Drupal to determine what name, version etc. to show while viewing module list. We will now create [i]mymodule.info[/i] file in mymodule folder. This file will contain following information:

[code]
name = My Custom Module
description = “Custom module to add custom functionality”
version = 7.x-1.x-dev
core = 7.x
project = rattanpal
[/code]

Most of this file is self-explanatory. Every module has a name, description, version and core. More information on these options can be found at http://drupal.org/node/542202. Next and last required file for adding a custom module is [i]mymodule.module[/i] file. This file controls options for module access, custom menu entries, module settings etc. Following is the code that we will put in our myodule.module file; which will be explained shortly.

[code type=”php”]
‘. t(“Displays Help for MyModule”) .’

‘;
break;
}
}
?>
[/code]

[i]mymodule_help[/i] is Hook to implement Help for your module. You will eventually want to enter more information for users to help them how to use your module. This is explained in detail at http://drupal.org/node/1095546

If you were osave these changed and go to admin/modules at this moment, you will see your module listed in list of modules. At this point, you should be able to enable/install your custom module.

We will continue with this in another tutorial where we will use this module to add a custom page. We can use that page to deliever any type of content (for example, ajax to server json content or a custom front page). We will also discuss how to use permissions to secure that page, if needed.

EDIT: Part 2 of this tutorial is at Drupal 7: Custom Module – Part 2.

March 4, 2015
by Jaswinder Rattanpal
0 comments

Drupal 7: Tweet from Drupal

I wanted to be able to post my from Drupal to Twitter without having to tweet it twice. I found this very nice Twitter module within Drupal to be able to do that. Some instructions are quite simple but it still took me around 2 hours to figure out which setting to use to tweet from Derupal.

Most of these instructions came from Sign in to drupal with your Twitter account page. But there is s very subtle detail that is needed to be able to post to Twitter and most of my time was spent on that; and I fround that option accidentally.

You will need to install OAuth and Twitter modules. I will not go into details as that is very staright forward. You will need to enable OAuthm, Twitter, Twitter Actions and Twitter Post modules; all Twitter modules are included in one Twitter module.

Before moving ahead with any settings, you will need to create an application in Twitter Developer enviroment; you will need consumer key and consumer secret from there. You will need to save these in admin/config/services/twitter. Following 2 steps need to be following before moving ahead:

  1. Give Read and Writeaccess in Application Typein Settings tab
  2. Create Access Tokenin Overview Tab
    1. This step needs to be performed after providing Read and Write access so your application will have write access to post
    2. This will allow this application access to your own account

After you are done creating that app, you will need to provide your site and user access to that application so it can post to your account. For that, you will need to go to users/USERNAME. Edit your account and then go to Twitter Accounts tab. Once there, click on Add Account. This will take you to a Twitter page which will ask you to confirm access to your site to post tweets in the Twitter user account; you will need to be logged in as that user or it will ask you to login as a user before proceeding. Click on Authorize App and it will take you back to your site where the request originated from ; Twitter account will be automatically added to your Twiter account list.

Last change you will need it make is to enable which content type will have Post to Twitter checkbox enabled. For that, you can go to admin/config/services/twitter/post. Check from which content type you want to post to Twitter. Save changes.

Now you are ready to post to Drupal and Twitter at the same time. Once you add/edit content in that that content type, you will have the option of posting to Twitter. By default, its not enabled. So, you will need to enable it for each post. 

This is it. Tweets from Drupal are just one content entry away.

March 4, 2015
by Jaswinder Rattanpal
0 comments

PHP: The Right Way

Found this site from one of the poster’s signature on www.sitepoint.com. Its not detailed but a great reminder of new things in PHP; at least I think it is. It also contains great links that are great read. Just wanted to share with you all. 

PHP: The Right Way