Please use the solution from mattandneil provided as a different answer and here How to get the DE-Orgs Namespaceprefix? (NOT the Namespaceprefix from the scope of an object or class) - the following is my old approach which for now works too, but I can not recommend it.
This is a tough nut to crack and I found only an ugly and hackish solution which requires high user privileges.
It seems that there is no clean direct method provided by the APIs to get the Org's Namespaceprefix. To clarify: we are NOT looking for a prefix from the scope of an installed managed package. Instead we are looking for the namespaceprefix which the org is providing. That means it's only existent in Developer Editions - never in Production environment. But if you create Apps, which might be installed in Dev-Orgs and Production Orgs and you don't I and have to deal with it dynamically you need to determine which is the prefix of you residing org. Again NOT the one from within which your doing the determination.
My workaround is - sadly and only out of frustration - to fetch the setup-page and parse the html-body for it. It might break, if Salesforce updates the setup.
This said, here comes my workaround:
public static string getOrgNamespacePrefix() {
string result = '';
string[] tds = new string[]{};
PageReference p = new PageReference('/0A2');
String html = '';
if(!Test.isRunningTest()) { html = p.getContent().toString(); }
html = html.replace('\r','');html = html.replace('\n','');
xr r = new xr ('<td class="summaryYes">(.*?)</td>', html );
// there are 0 to 3 matches, BUT only if there are exactly 3 matches, the third one is the namespace!
while(r.find()) {
tds.add(r.group(1));
}
if(tds.size()==3) result=tds.get(2);
return result;
}
with xr
is only a wrapper for ease+convenience around standard regexp (you can get rid of it, if you don't like it just by replacing it.
public without sharing class xr {
public static xr build(string regex, string haystack) {
return new xr(regex,haystack);
}
public pattern p;
public matcher m;
public xr(string regex, string haystack) {
p = pattern.compile( regex );
m = p.matcher(haystack);
}
public boolean find() {
return m.find();
}
public string group(integer i) {
try {
return m.group(i);
} catch(exception e) {
return null;
}
}
public integer end(integer i) {
try {
return m.end(i);
} catch(exception e) {
return null;
}
}
public integer start(integer i) {
try {
return m.start(i);
} catch(exception e) {
return null;
}
}
public string pick(integer i) {
//if(m.find()) return m.group(1); else return '';
if(m.find()) return m.group(i); else return '';
}
}