How to get the current version of package in apex
Let me ask a simple question to all the salesforce developer. Have you ever wondered about showing the current version on the bottom of your managed package? Like the various application show, at the bottom right corner, or in the about section of the application. Let me assume that yes you are one of the most developers who have thought about it. Implementing it does not seems like too big of a task, in the controller which is linked to the required page, create a string type variable and then store the version in that variable. To compare the version convert it into decimal and then work with the obtained value. However how are you supposed to distinguish that 1.14 is higher version than 1.2? Decimal will tell 1.2 to be higher value, hence it all fails. Let me give a proper solution to this problem, an in the process show you, how to get the current version of package in apex.
APEX class
Before we dive into the apex class code, let me tell you, this method only works if you have a manged package in your org. Without the managed package this method won’t work. With that said, let’s hop onto the code.
public class pckgversion { public version ver { get; set;} public integer major { get; set;} public integer minor { get; set;} public pckgversion(){ ver = System.requestVersion(); major = ver.major(); minor = ver.minor(); } public integer getCompare(){ return (ver.compareTo(new version(1,2))); } }
As you can see in this class that we are using a version type of variable. This class is used to store and compare various versions. There are four methods of this class, major(), minor(), patch(), and compareto(). The current package version is fetched with the help of system class function requestFunction(). All the functions are self explanatory in this example, with the exception of one function that is compareto(). This function first compares the major version, if that is same, then it compares the minor version and then the patch version. If any version if different, then it returns the difference in that version.
Visualforce Code
I have also made a small Visualforce page for this example whose code is as follows.
<apex:page controller="pckgversion"> <apex:outputtext value="Version is: {!ver}"/><br/> <apex:outputtext value="Major Version is: {!major}"/><br/> <apex:outputtext value="Minor Version is: {!minor}"/><br/> <apex:outputtext value="Compare Version: {!compare}"/> </apex:page>
Support
That’s all about getting current package version in apex, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views on how to make this code better, in comments section below.