Friday, August 23, 2013

About sharing that I misunderstood

Sharing means caring literally.In salesforces, with sharing means I want to share based on the rules.

By default, Apex class does not effected by  current user's permissions, field-level security, and sharing rules.Because it run in system context.Oh,please note this is not include Apex code that run in Execute Anonymous.Code in Execute Anonymous still effected by permission of the current user.

So this is the reason why with sharing and without sharing keywords come for.But only to control sharing rules.

Use with sharing to enforce the sharing rules that apply to the current user.

Use without sharing  to ensure that the sharing rules for the current user are not enforced.

How about if the class use neither with sharing or without sharing? Still the current sharing rules remain in effect.

All the details can be check at Using the with sharing or without sharing Keywords .

Actually why suddenly I babbling about sharing?Because it cause me headache  for almost whole day.

I got this one line of code in one Apex class

 
for (AggregateResult ar : [Select Name, max(Employee) Emp, Account__r.Name AccName  
      from Location__c  Where Account__c != null and Status__c = 'Approved' 
       group by Name,Account__r.Name order by Name])
{
  system.debug('@MYTEST Name=' +(String)ar.get('Name')+' , Account Name ='+(String)ar.get('AccName'));
}


The issue that I face, when ever I run my application the Account Name returning null value while actually I knew it should return some value.

I run the query in Workbench , it 's returning the data.I run in Developer console, it also returning data.But when I try to execute it from UI,the value not coming out in Monitoring Debug log.

I never thought the issue is caused by this sharing stuff.After struggling whole day, I discussed with my colleague and she suggesting to remove with sharing  keyword from the class.

After I have done that, my problem puff away.The value printing as usual.Now I can see that with sharing is not mean sharing is caring or you can share the data to everyone.It means, the sharing will be restricted or  can say that actually I can put it if I want to share certain data only.

Use with sharing when you only want to share certain thing.If you want to share it to all,do not use with sharing.