• RIteshM
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 35
    Questions
  • 6
    Replies

My CreateTimeLine code is

 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){
Map<Id,User> userMap = new Map<Id,User>([Select id,Name From User where Authorize__c = true]);
Map<Id,GlassUserApiSettings__c> userSettingsMap = new Map<Id,GlassUserApiSettings__c>();

for(Id user_id : userMap.keySet()){
GlassUserApiSettings__c userSettings = GlassUserApiSettings__c.getValues(user_id);
if(userSettings == null)
{ User u =userMap.get(user_id);
u.Authorize__c = false;
update u;
}
else userSettingsMap.put(user_id,userSettings);

}
for(sObject obj : objList)
for(Id userId: userSettingsMap.keySet() ){
String type = '';
if(contentMap.get('Object').equals('FeedItem'))
type='Post';
if(contentMap.get('Object').equals('FeedComment'))
type= 'Comment';
GlassUserApiSettings__c userSettings = userSettingsMap.get(userId);
if(((String)obj.get(contentMap.get('Content'))).contains('@'+userMap.get(userId).Name)){
Datetime tokenExpiredTime = userSettings.LastModifiedDate;
tokenExpiredTime.addSeconds(Integer.valueOf(userSettings.ExpireDuration__c));
String body='{"html":"<article><section><div class="text-auto-size">'+type+':'+
'<p class="yellow">"'+obj.getSObject('CreatedBy')+'&nbsp;'+obj.getSObject('CreatedBy')+'</p><p>'+obj.get(contentMap.get('Content'))+'</p>'+
'</div></section> </article>"}';
System.debug('Body is '+body);
/* if(tokenExpiredTime >= System.now()){
GMirror.TokenResponse res = GMirrorUtil.refreshToken(userSettings.RefreshToken__c);
userSettings.RefreshToken__c = res.refresh_token;
userSettings.AccessToken__c = res.access_token;
userSettings.ExpireDuration__c = Integer.valueOf(res.expires_in) ;
update userSettings;
}*/
String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);
GMirror.TimelineResponse createdTimeCard = (GMirror.TimelineResponse) JSON.deserialize(timelineRes,GMirror.TimelineResponse.class);
if(createdTimeCard.id != null)
System.debug('created timeline card :'+createdTimeCard);
else { try{
throw new GMirror.TimelineException(null,timelineRes);
}
catch(Gmirror.TimelineException e){
System.debug(e.getMessage());
}
}
}
}
}

 

and My Batch apex code is 

 

public class BatchPublishTimeLine implements Database.Batchable<sObject>{
sObjectIterable iterable;
Map<Id,User> userMap;
Map<String,String> contentmap;

public BatchPublishTimeLine(List<sObject> objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

 

public static String doAPICall(String postBody, String method, String endPoint, String accessToken){

HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse res;

req.setEndpoint(endPoint);
req.setMethod(method);
req.setHeader('Content-Type','application/json');

if(method == 'POST' || method == 'PUT')
req.setBody(postBody);
req.setHeader('Authorization','Bearer ' + accessToken);
res = http.send(req);
String result = res.getBody();
System.debug('status code is '+res.getStatus());
System.debug('result is'+res.getBody());
return result;
}

i am calling batch apex from a trigger after in sert function i am getting this error from line 

 

String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);

i am not using any DML statement after doApiCall function as you can see . but why i am facing trhis error ??Please guideline to resolve it.

  • September 25, 2013
  • Like
  • 0

riggeri am testing a trigger.i am calling this method

  GMirrorUtil.createTimeLine(Trigger.new, contentMap);

My create timeline function is 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){ 
      Map<Id,User> userMap = new Map<Id,User>([Select id,Name From User where Authorize__c = true]);
      Map<Id,GlassUserApiSettings__c> userSettingsMap = new Map<Id,GlassUserApiSettings__c>();

       for(Id user_id : userMap.keySet()){
         GlassUserApiSettings__c userSettings = GlassUserApiSettings__c.getValues(user_id);
        if(userSettings == null)
         { User u =userMap.get(user_id);
            u.Authorize__c = false;
           update u;  
         }
          else userSettingsMap.put(user_id,userSettings); 

       }
       for(sObject obj : objList)
         for(Id userId: userSettingsMap.keySet() ){
           String type = '';
           if(contentMap.get('Object').equals('FeedItem'))
             type='Post';
           if(contentMap.get('Object').equals('FeedComment'))
             type= 'Comment';
           GlassUserApiSettings__c userSettings = userSettingsMap.get(userId);
           if(((String)obj.get(contentMap.get('Content'))).contains('@'+userMap.get(userId).Name)){
             Datetime tokenExpiredTime = userSettings.LastModifiedDate;
             tokenExpiredTime.addSeconds(Integer.valueOf(userSettings.ExpireDuration__c)); 
             String body='{"html":"<article><section><div class="text-auto-size">'+type+':'+
                         '<p class="yellow">"'+obj.getSObject('CreatedBy')+'&nbsp;'+obj.getSObject('CreatedBy')+'</p><p>'+obj.get(contentMap.get('Content'))+'</p>'+
                         '</div></section> </article>"}';
                         System.debug('Body is '+body);
             if(tokenExpiredTime >= System.now()){
               GMirror.TokenResponse res  =  GMirrorUtil.refreshToken(userSettings.RefreshToken__c);                 
               userSettings.RefreshToken__c = res.refresh_token;
               userSettings.AccessToken__c  = res.access_token;    
               userSettings.ExpireDuration__c = Integer.valueOf(res.expires_in) ;
               update userSettings;
             }
             String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);
             GMirror.TimelineResponse createdTimeCard  = (GMirror.TimelineResponse) JSON.deserialize(timelineRes,GMirror.TimelineResponse.class);   
             if(createdTimeCard.id != null)
               System.debug('created timeline card :'+createdTimeCard);
             else { try{
                        throw new GMirror.TimelineException(null,timelineRes);
                       }
                    catch(Gmirror.TimelineException e){
                      System.debug(e.getMessage());
                    }
                  }
           }
         }          
    }

but when i initialize prepare String body='{"html":"'+type+':'+ '"'+obj.getSObject('CreatedBy')+' '+obj.getSObject('CreatedBy')+'

'+obj.get(contentMap.get('Content'))+'

'+ ' "}'; i check it in debug logs its giving me null for getSObject('CreatedBy'); i inserted it in my test class thats why trigger invoked and i am using afterinsert event in trigger . can any one please tell why its giving me null ??

 

 

  • September 25, 2013
  • Like
  • 0

i am trying to test a trigger my trigger code is 

 

trigger PostFeedsToTimeLine on FeedItem (after insert) {
Map<String,String> contentMap = new Map<String,String>{'Object' =>'FeedItem','Content' =>'Body'};
if(Trigger.new.size() > 5){
BatchPublishTimeLine publishBatch = new BatchPublishTimeLine(Trigger.new,contentMap);
Database.executeBatch(publishBatch,5);
}
else GMirrorUtil.createTimeLine(Trigger.new, contentMap);
}

 

batch will always get created if size is greater than 5 but when size is greater than 5 two batch will get executed  what to do.in batch i am calling GMirrorUtil.createTimeLine which is making two callouts thats why this 5 limit .what to do in this case ?? because maximum 5 batch can be queued thats why if possible i try to make it without batch but in cases when more than 5 then i execute it using Batch.

  • September 25, 2013
  • Like
  • 0

My Test function is 

 

@isTest(SeeAllData=true)
static void test1(){
MirrorTestUtil.setupSettings();
User u = [Select Authorize__c From User Where Id = :UserInfo.getUserId()];
u.Authorize__c = true;
update u;
List<FeedItem> feedList= new List<FeedItem>();
for (Integer i = 0; i<10;i++)
feedList.add( new FeedItem(Body='Hello World'+i,ParentId = UserInfo.getUserId()));
Test.startTest();
insert feedList;
Test.stopTest();
}

 

as u can see i updated User Authorize__c = true;

from this a trigger get called after that because its bulk that why i am doing my operation as Batch apex .code for that is here 

public class PublishGlassTimeLine implements Database.Batchable<sObject>{
SObjectIterable iterable;
Map<Id,User> userMap;
Map<Id,GlassUserApiSettings__c> userSettingsMap;
Map <String,String> contentmap;

public PublishGlassTimeLine(List<sObject>objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
userSettingsMap = new Map<Id,GlassUserApiSettings__c>();
System.debug('user map is '+userMap);
System.debug('user map values are '+userMap.Values());
for(User user: userMap.Values())
userSettingsMap.put(user.Id,GlassUserApiSettings__c.getValues(user.Id));
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

its giving me error

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PostFeedsToTimeLine: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.BatchPublishTimeLine.<init>: line 11, column 1
Trigger.PostFeedsToTimeLine: line 4, column 1: []

he is referring null object to userMap.

but i think it should not be null.

can any one please tell why i am facing this NullPointer exception ??

 

  • September 25, 2013
  • Like
  • 0

i have a custom setting that is Public and have to test for DMLException.i am doing one thing creating and inserting as one usere and calling the delete method as secong user which will not have access to This custom settings.i want to know is custom settings available for all profiles because its not throwing any exception my Apex function is 

 

  public PageReference deleteUserSettings(){

       try{        delete userSettings;       

  userSettings = new GlassUserApiSettings__c(setUpOwnerId = UserInfo.getUserId());

             }   

   catch (System.DMLException e){System.debug(e);} 

      return null;    }

 

and my test code is

 

@isTest(SeeAllData=true)
static void testDeleteApiSettingsN(){
MirrorTestUtil.setupSettings();

Profile p = [SELECT Id FROM Profile WHERE Name='Read Only'];
User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@orgtest.com');
MirrorSettingsController ctrl = new MirrorSettingsController();
System.runAs(u2) {
Test.startTest();
ctrl.deleteUserSettings();
Test.stopTest();
}
}

 

i tried it with Stasndard User as well but its deleting not throwing exception. can any one please tell how to make code coverage of this to DMLException .

  • September 25, 2013
  • Like
  • 0

i am trying to test my Controller .One doubt is in using Test.startTet and Test.stopTest().i am checking every method in separate unit test . for example

static testmethod void testEditApiSettings(){
         MirrorTestUtility.getApiSettings();
    Test.startTest();
    MirrorSettingsController ctrl = new MirrorSettingsController();   
  ctrl.setEditApiSettings();
  Test.stopTest();
System.assert(ctrl.editApiSettings,'Method perform to Show Insert view# Not able to set ');
}
static testmethod void testDeleteApiSettings(){
MirrorTestUtility.setUpSettings();
Test.startTest();
MirrorSettingsController ctrl = new MirrorSettingsController();
ctrl.deleteUserSettings();
Test.stopTest();
 GlassUserApiSettings__c userSettings =  GlassUserApiSettings__c.getValues(UserInfo.getUserId());
System.assert(userSettings== null ,'User settings are present ence Method don\'t delete Usetr Settings' );
}

so you can see i create ctrl every time in test.startTest() is this more appropriate or creating it before Test.startTest();

  1. there is a DML exception perhaps that cant come because DML limit is 100 and i am hardly using 2-3 in my controller. i write a function

    public PageReference deleteUserSettings(){
    try{  
    delete userSettings;  
    userSettings = GlassUserApiSettings__c.getValues(Userinfo.getUserId());
    }
    catch(System.DmlException e){System.debug(e); }
    return null;
     }

    how to test this should i remove this try catch block (because exception is not expected)??How to test this catch block please guideline .

  • September 25, 2013
  • Like
  • 0

i want to create a custom exception. In this Exception i want to make a constructor which take one string arguments and append in getMessage .How to accomplish this.

 public class TimelineException extends Exception{
  private String message;
    public override String getMessage(){
      return 'Not able to post to Timeline.getting response from Api : '+ message;
    }
  }

main problem i am facing is when i use this public TimelineException(Sting x){ } then its give me error

Save error: System exception constructor already defined: (String) GMirror.cls /Google Salesforce Integration/src/classes.

  • September 24, 2013
  • Like
  • 0

i am trying to understand OR ,AND and NOT operator in rendered attribute.itried some but not successful. for example

 

tried one  experiment 

 

rendered="{! IF(AND($Profile.Name !='System Administrator',OR(apiSettingsReady,NOT(editApiSettings))),false,true)}" .is this also a right operation or not?? its not working as expected. Please guideline any link for using AND and OR operator in nested way is this possible or not ??

  • September 23, 2013
  • Like
  • 0

How to know the Logged in user accessing visualforce page is Admin or not using apex. i want to do this using my custom controller .i know in visualforce we can do like this $Profile.Name =='System Administrator' but how to accomplish it in apex code ??

  • September 23, 2013
  • Like
  • 0

if there is a visualforce element then we set visibility according to the redered attribute . =but i have to set visibility of visualforce according to data of html element

    <p style="display:{! IF(userSettings == null && $Profile.Name !='System Administrator','visible','hidden')}">Click on the authorize to authorize your self to Google GLASS Account &nbsp;<apex:commandButton value="Authorize" action="{! authorizeApp}"  />

i want to set visibility but its showing me the p element in every case.please guideline how to do this ??

  • September 22, 2013
  • Like
  • 0

i am trying to delete a custom setting named as LAB_Google_API_Settings__c .when i try to delete it is showing a page and message that

 

This custom object is used by another feature. Remove the usage and try again. and that another feature is a Visualforce Page . my page code is 

 

<apex:page controller="Mirror_Settings_Controller">

<apex:form id="pageBlock1" rendered="{! IF($Profile.Name !='System Administrator',false,true)}">
<!-- redirect to custom settings configuration -->
<apex:pageMessages id="theMessages"/>
<apex:pageBlock title="Google Glass Configuration" rendered="{!(!apiSettingsReady || editApiSettings)}" >
<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!saveGoogleSettings}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel value="Client Id"/>
<apex:inputText value="{!apiSettings.ClientId__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Client Secret"/>
<apex:inputText value="{!apiSettings.ClientSecret__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Scope"/>
<apex:inputText value="{!apiSettings.Scope__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Redirect Uri" />
<apex:inputText value="{! apiSettings.RedirectUri__c}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
<apex:form id="pageBlock2" rendered="{! IF($Profile.Name !='System Administrator',false,true)}">
<apex:pageBlock title="Google Glass Configuration" rendered="{! (apiSettingsReady && !editApiSettings)}" >
<apex:pageBlockButtons location="top">
<apex:commandButton value="Authenticate" action="{!authorizeApp}"/>
<apex:commandButton value="Edit" action="{! editApiSetting}" reRender="pageBlock1,pageBlock2"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel value="Client Id"/>
<apex:outputText value="{!apiSettings.ClientId__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Client Secret"/>
<apex:outputText value="{!apiSettings.ClientSecret__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Scope"/>
<apex:outputText value="{!apiSettings.Scope__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Redirect Uri" />
<apex:outputText value="{! apiSettings.RedirectUri__c}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
<apex:form id="pageBlock3">
<!-- redirect to custom settings configuration -->
<apex:pageBlock title="User's Credentials" rendered="{!IF(userSettings !=null, true, false)}" >
<apex:pageBlockButtons location="top">
<apex:commandButton value="Delete" action="{! deleteUserSettings}" reRender="pageBlock1,pageBlock3"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel value="Access Token"/>
<apex:outputText value="{!userSettings.Access_Token__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Refresh Token"/>
<apex:outputText value="{!userSettings.Refresh_Token__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Validation Time(in Seconds)"/>
<apex:outputText value="{!userSettings.Expire_Duration__c}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Last Modified" />
<apex:outputText value="{! userSettings.LastModifiedDate}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>

</apex:page>

 

the thing that is surprising me is no Apex class is showing as component and i am unable to figure it out where i used this custom setting in visualforce page.if some variable are shown then it also show in Controller.it is giving me error only on visualforce page.please guideline how to delete this custom setting ??

 

  • September 21, 2013
  • Like
  • 0

i have a custom object . one field i want to make as master-detail with User object such that when user is deleted .Object is also deleted.but when i try to make the master-detail relationship .it is not showing User Object.can any one please tell why and how to resolve it ??

  • September 21, 2013
  • Like
  • 0

i am trying to develop visualforce page. i want to make a call. iwrite a code 

 

public class SampleClass{

String account = 'XXXXXXXXXXXXXXXXXXX';
String token = 'YYYYYYYYYYYYYYYYYY';

public PageReference hello(){
TwilioRestClient client = new TwilioRestClient(account, token);

Map<String,String> params = new Map<String,String> {
        'To'   => '+919953938584',
        'From' => '+919910728457',
        'Url' => 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient'
    };
TwilioCall call = client.getAccount().getCalls().create(params);
return null ;

}

}

 

and vsualforce page

 

<apex:page controller="SampleClass">

    <apex:form >
            <apex:commandButton action="{!hello}" value="Make a Call"/>
    </apex:form>

</apex:page>

 

 

both the numbers are verified so call is going and a music is playing.now i want that when the user click  make a call button then he can talk to the dialled phone number.means his voice went to the number which is dialled and he can hear that voice.in other way that user can dial a phone number and talk to a  person using only browser .is this possible .Please guideline .

  • September 17, 2013
  • Like
  • 0

i write a visualforce page

 

<apex:page controller="sampleCon">
<apex:form>
<apex:selectList value="{!countries}" size="1" onselect="searchFeeds();">
<apex:selectOptions value="{!items}"/>
</apex:selectList>
<script type="text/javascript">
function searchFeeds(){
alert('Hello world');
}
</script>
<p/>
</apex:form>
<chatter:newsfeed />
</apex:page>

 

and controller code is 

 

public class sampleCon {
String countries ;

public PageReference test() {
return null;
}

public List<SelectOption> getItems() {
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('US','US'));
options.add(new SelectOption('CANADA','Canada'));
options.add(new SelectOption('MEXICO','Mexico'));
return options;
}

public String getCountries() {
return countries;
}
public void setCountries(String countries) {
this.countries = countries;
}
}

 

when i select any different country from select list no alert is shown by the browser. can any one please point me why ??

  • September 10, 2013
  • Like
  • 0

There is a Tab named as Files in dev org by default.there are some files init. can anyone guideline how to get access to these files through Apex and  there content as Blob data type. i want to know id of these files through SOQL then how to do that

i write a code in apex for setting the chatter photo of a user . iwrite a function

 

public PageReference setPhoto(){

Http h = new Http();
HttpRequest req = new HttpRequest();
string firstImageURL = 'https://ap1.salesforce.com/resource/1377118388000/sample_pic';
firstImageURL = firstImageURL.replace(' ', '%20');
req.setEndpoint(firstImageURL);
req.setMethod('GET');
req.setHeader('Content-Type', 'image/jpeg');
req.setCompressed(true);
req.setTimeout(60000);
HttpResponse res = null;
res = h.send(req);
blob image = res.getBodyAsBlob();
ConnectApi.BinaryInput bb=ConnectApi.BinaryInput(image, 'image/png','myfile');
System.debug('user is'+ConnectApi.ChatterUsers.setPhoto(null,'00590000001jFln',bb));
return null;

}

 

when i try to save it it is giving me error  

Error: Compile Error: Method does not exist or incorrect signature: ConnectApi.BinaryInput(Blob, String, String) at line 28 column 27

 

 

and i am following this http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_inputs.htm#capi_binary_input 

can you please guideline whether this documentation is wrong or right ?? and how to get ConnectApi.BinaryInput instance

i am trying to set value of custom url field to a visualforce page to for that i need domain oring prefix like ap1.salesforce.com or na1.salesforce.com .how to get that in UI it is showing some global objects $Organization,$Profile,$System,$User,$UserRole which object should be used and which field please tell

i am trying to modify default Name field type to autonumber . when i put in DisplayFormat CAT-{0001} its giving me error on save Error: Invalid substitution variable .can any one please tell what should be in Display Format field to be valid string ??

i am trying to update a ObjectPermissions Object in slaesforce such that a profile will get the permissions to access a object similar to other profile.

i write a code

 

my code segment is 

 

PermissionSet set1 = [SELECT Id From PermissionSet Where profileId= :SourceProfileId LIMIT 1] ;
PermissionSet set2 = [SELECT Id FROM PermissionSet Where profileId= :TargetProfileId LIMIT 1];
List<ObjectPermissions> oo = [SELECT Id,SObjectType,ParentId,PermissionsCreate,PermissionsDelete,PermissionsEdit,PermissionsModifyAllRecords,PermissionsRead,PermissionsViewAllRecords FROM ObjectPermissions WHERE ParentId = :set1.id];


List<ObjectPermissions> oo1 = [SELECT ParentId,Id,SObjectType,PermissionsCreate,PermissionsDelete,PermissionsEdit,PermissionsModifyAllRecords,PermissionsRead,PermissionsViewAllRecords FROM ObjectPermissions WHERE ParentId = :set2.Id] ;
Map<String , ObjectPermissions> source_obj = new Map<String,ObjectPermissions>();
Map<String , ObjectPermissions> target_obj = new Map<String,ObjectPermissions>();
for(ObjectPermissions o : oo)
{
source_obj.put(o.SObjectType,o);
}
for(ObjectPermissions o : oo1)
{
target_obj.put(o.SObjectType,o);
}
ObjectPermissions target,source;
for(String s : source_obj.keySet() )
{ if(target_obj.containsKey(s))
{ target = target_obj.get(s);
source = source_obj.get(s);
System.debug('Source is:'+source);
System.debug('Target is : '+target);
target.PermissionsCreate = source.PermissionsCreate;
target.PermissionsDelete = source.PermissionsDelete;
target.PermissionsEdit = source.PermissionsEdit;
target.PermissionsModifyAllRecords = source.PermissionsModifyAllRecords;
target.PermissionsRead = source.PermissionsRead;
target.PermissionsViewAllRecords =source.PermissionsViewAllRecords;
update target;
}
else {target = new ObjectPermissions(SObjectType = s );
source = source_obj.get(s);
target.PermissionsCreate = source.PermissionsCreate;
target.PermissionsDelete = source.PermissionsDelete;
target.PermissionsEdit = source.PermissionsEdit;
target.PermissionsModifyAllRecords = source.PermissionsModifyAllRecords;
target.PermissionsRead = source.PermissionsRead;
target.PermissionsViewAllRecords =source.PermissionsViewAllRecords;
insert target; }
}

 

when the control come to this line 

 

update target;

it is giving error 

 

Update failed. First exception on row 0 with id 110i0000007KNEvAAO; first error: INVALID_CROSS_REFERENCE_KEY, You can't create, edit, or delete records for this permission set parent because it's associated with a profile. Parent ID: 0PSi00000009BE9: []

 

i am unable to figure it out why i am facing this error please some one help to resolve this error

i am following this tutorial http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_permissionset.htm . i read this and have to get the information related to a profile . that a particular profile have access to which level to a object .for example Authenticated website have access to which level to a object say Account  have read only access or read/write or viewall etc and then after reading  giving it all kind of access read,write,viewall,modifyall etc.for getting object permissions i write a query

 

List<ObjectPermissions> oo1 = [SELECT Id FROM ObjectPermissions WHERE Parent.profileId = :TargetProfileId] ;

 

but i dont know any thing about ObjectPermissions object .how to get access properties related to a object for example i want to access properties of object Account and then want to modify it.can any one tell how to use this object and the properties related to this Object please guideline so i can proceed further 

 

 

hi i am sending only a single Http Request in Batch but still facing error System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

 

My test code is 

 

@isTest(SeeAllData=true)
static void test1(){
MirrorTestUtil.setupSettings();
User u = [Select Authorize__c From User Where Id = :UserInfo.getUserId()];
u.Authorize__c = true;
update u;
System.debug('u is '+u);

List<FeedItem> feedList= new List<FeedItem>();
for (Integer i = 0; i<5;i++)
feedList.add( new FeedItem(Body='@'+UserInfo.getName()+'Hello World'+i,ParentId = UserInfo.getUserId()));
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());

insert feedList;
Test.stopTest();
}

 

and My trigger code is 

trigger PostFeedsToTimeLine on FeedItem (after insert) {

BatchPublishTimeLine publishBatch = new BatchPublishTimeLine(Trigger.new,contentMap);
Database.executeBatch(publishBatch,5);
}

 

and My Batch class code is 

public class BatchPublishTimeLine implements Database.Batchable<sObject>{
sObjectIterable iterable;
Map<Id,User> userMap;
Map<String,String> contentmap;

public BatchPublishTimeLine(List<sObject> objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

 

and My createTimeLine function code is 

 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){

String timelineRes = doApiCall('xyzzz','POST','https://www.googleapis.com/mirror/v1/timeline','xxxxxxxxx');

}

 

doApiCall code is 

public static String doAPICall(String postBody, String method, String endPoint, String accessToken){

HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse res;

req.setEndpoint(endPoint);
req.setMethod(method);
req.setHeader('Content-Type','application/json');

if(method == 'POST' || method == 'PUT')
req.setBody(postBody);
req.setHeader('Authorization','Bearer ' + accessToken);
res = http.send(req);
String result = res.getBody();
System.debug('status code is '+res.getStatus());
System.debug('result is'+res.getBody());
return result;
}

 

and the Mock class code response is 

 

@isTest
global class MirrorMockTimelinePostImpl implements HTTPCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('https://www.googleapis.com/mirror/v1/timeline', req.getEndpoint());
System.assertEquals('POST', req.getMethod());
System.assert(req.getHeader('Authorization').startsWith('Bearer'));

// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"kind":"mirror#timelineItem", "id":"mockid", "created":"2013-07-31T12:07:34.882Z", "updated":"2013-07-31T12:07:34.882Z", "etag":"\\"ZECOuWdXUAqVdpmYErDm2-91GmY/NVMWuR8LJyCKttsmne9R4K8n7YI\\"", "text": "New Lead: OauthCheck EarlyAm, Google, Inc., (234) 567-8900"}');
res.setStatusCode(200);
return res;
}
}

 

and i am unable to figure it out how using only one callout its throwing an error ?? Please help

  • September 26, 2013
  • Like
  • 0

if there is a visualforce element then we set visibility according to the redered attribute . =but i have to set visibility of visualforce according to data of html element

    <p style="display:{! IF(userSettings == null && $Profile.Name !='System Administrator','visible','hidden')}">Click on the authorize to authorize your self to Google GLASS Account &nbsp;<apex:commandButton value="Authorize" action="{! authorizeApp}"  />

i want to set visibility but its showing me the p element in every case.please guideline how to do this ??

  • September 22, 2013
  • Like
  • 0

i write a code in apex for setting the chatter photo of a user . iwrite a function

 

public PageReference setPhoto(){

Http h = new Http();
HttpRequest req = new HttpRequest();
string firstImageURL = 'https://ap1.salesforce.com/resource/1377118388000/sample_pic';
firstImageURL = firstImageURL.replace(' ', '%20');
req.setEndpoint(firstImageURL);
req.setMethod('GET');
req.setHeader('Content-Type', 'image/jpeg');
req.setCompressed(true);
req.setTimeout(60000);
HttpResponse res = null;
res = h.send(req);
blob image = res.getBodyAsBlob();
ConnectApi.BinaryInput bb=ConnectApi.BinaryInput(image, 'image/png','myfile');
System.debug('user is'+ConnectApi.ChatterUsers.setPhoto(null,'00590000001jFln',bb));
return null;

}

 

when i try to save it it is giving me error  

Error: Compile Error: Method does not exist or incorrect signature: ConnectApi.BinaryInput(Blob, String, String) at line 28 column 27

 

 

and i am following this http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_inputs.htm#capi_binary_input 

can you please guideline whether this documentation is wrong or right ?? and how to get ConnectApi.BinaryInput instance

i have to clone an object means copy all fields in another object. all the fields will remain same except one which is not writable .first thing is in sObject.clone() function how is it possible to have two objects having same Id.Please explain a little workflow and input and output of clone function