function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Baird StraughanBaird Straughan 

Reliable method of pulling Salesforce server name for URL

I'm creating a VF page with all our dashboards in it, and I need this to be deployable across multiple instances.  The VF page extracts the HTML from the Dashboards page via 
PageReference dbPage = new PageReference(SFServerURL + '/' + DashboardId);
                Blob pageBlob = dbPage.getContent();
                DashboardBlobString = pageBlob.toString(); 
The trick is to ge the write SFServerURL, because at this moment the current system URL is pointed to the Visualforce page, 
https://c.na3.visual.force.com/apex/WGDashboardsPage
And that's required me to figure out how to discard the "c." and the "visual.force." etc. and get back to the internal UI's base URL, which is "https://na3.salesforce.com", and to come up with a method which is reliable for all the deployments.
After much searching through the various message boards here's what I came up with, which I believe is more reliable than other versions I've seen, so I'm sharing it.  If you can suggest improvements, please do.
 
string SFServerURL = URL.getSalesforceBaseURL().toExternalForm(); 
        // Use .substringBetween() because we don't know how many characters are in the server name
        string SFInstance = SFServerURL.substringBetween('https://','.');
        // But sometimes Salesforce inserts a "c." in front of the server number, so SFINstance is just "c"
        // Since Salesforce may decide to use other prefixes in the future ...
        if (SFInstance.length()==1) {
            string HTTPSMask = SFServerURL.LEFT(10);
            SFInstance = SFServerURL.substringBetween(HTTPSMask,'.');
        }
        SFServerURL = 'https://' + SFINstance + '.salesforce.com';
        try{
        id DashboardId = [select id from Dashboard where DeveloperName = 'WG_Dashboard'][0].id;
        system.debug('URLstring for dashboards is '+ SFServerURL + '/' + DashboardId);
        PageReference dbPage = new PageReference(SFServerURL + '/' + DashboardId);
                Blob pageBlob = dbPage.getContent();
                DashboardBlobString = pageBlob.toString(); 
        } catch(Exception e){
            apexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,
                       'Please tell WaterGrass support about this error: '+e));
        }
I'm looking forward to your suggestions.