• Sumant Kuchipu 1
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 4
    Replies
Hi, 
We have custom attachment which attach the files to BOX (using REST API) and rendering attachment from there when the user clicks on "View" link. But the following functionolity works on PDF and image files, they are directly opening on next tab/window but when we click on Docs or CSV, the file is downloading direclty rather opening  on new page. Please someone give me clues on this? see the following code snippet.
Apex Code: 
public String fileOpen(){
     HttpRequest req = new HttpRequest();
     req.setEndpoint(fileDownloadURL);
     req.setMethod('GET');
     Http binding = new Http();
     HttpResponse res = binding.send(req);
     Blob boxFile = res.getBodyAsBlob();
     String boxResponse = 'data:'+res.getHeader('Content-Type')+';base64,'+EncodingUtil.base64Encode(boxFile );
     return boxResponse ;
}
VisualForce Page:
<apex:page controller="BoxController" action="{!fileOpen}">
    <apex:form >
        <apex:outputText escape="false" value="{!boxResponse}"/> 
    </apex:form>
</apex:page>

Please help me on rendering doc/csv files on page rather downloading.. 

Appreciate your help..
Sumant K
 
Hi,
When a user clicks on a link, I called VisualForce and then call Apex that calls REST api to "box" and gets download link. I was able to download file from that link provided by BOX using REST api. (see download link below, I made it short since the download link is too big) .
and the file is directly downloading in the next page but I need to open the file instead of downloading

This is download Link returned from Box api:
https://dl.boxcloud.com/d/1/4cp_Tu5yjx8avwjkdIwL1Z4Du4iV8FkvvpQsFPco4fbvdvOvusVR7N89Tca-QOGarhUBNEBV5gKgCh6mj4z1n7URaroUCkRvnD5bTei5U1AuQ33BA../download
VisualForce:
<apex:page controller="BoxController" action="{!fileOpen}">

</apex:page>
Apex Code:
 
public PageReference fileOpen(){
        PageReference page;
        try{
            String bFileId=String.valueof(ApexPages.CurrentPage().getparameters().get('bFileID'));
            String fileDownloadURL= fileFromBoxDownload(bFileId);// This api calls to Box api and get download URL, which is avove link
            page = new PageReference(fileDownloadURL);
            page.setRedirect(true);
            
        } catch (Exception e){
            System.debug(' **** File fileOpen Exceptions '+e);
        }
        return page;
    }

Is there any possiblities to convert that Download to open on new window or same window? 
That would be great if anyone could give the clue, I apreciate your help. 

Thanks,
Sumant
Hi,

I'm trying to open/download a file returned from box.

when we click on a "Cleck Me" link, it calls the VF page and calls the Apex .. but I'm not sure how to open/download page from apex
Image and code are below.

User-added image

VF page:
<apex:page controller="BoxController" action="{!fileOpen}">

</apex:page>

Apex code:
 
try{
            String bFileId=String.valueof(ApexPages.CurrentPage().getparameters().get('bFileID'));

            String aToken = api.getAccessToken();
            if(bFileId!=null && bFileId!=''){
                String endPointURLToViewFile='https://api.box.com/2.0/files/'+bFileId+'/content';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endPointURLToViewFile);
                req.setMethod('GET');
                req.setHeader('Authorization', 'Bearer ' + aToken);
                req.setHeader('Content-Type','application/json');
                req.setHeader('Accept','application/json');
                req.setTimeout(120000);
                Http http = new Http();
                HTTPResponse res = http.send(req);
                
                String downloadURL=res.getHeader('Location');

            }
        }catch (Exception e){
            System.debug(' **** File Download Exceptions '+e);
        }
    }

Here I can get "downloadURL" but I don't know how to call this URL to opan/download with that URL.
Could someone please help me on this? 

Thanks,
Sumant K
 
Hi,
Here is the scenario, I have a custom attachment object and has a field  "View Attachment" (type formula)  with link to call apex and that apex making calls to "box" to download file. In Apex can we open that downloaded file direclty when the user clicks on Custom Attachment's "View Attachment" link? if yes, please give me some clue on that scenario open file directly from apex ? 

Thanks,
Sumant K
Hi,

We are developing customized attachments to upload documents to BOX. for this I needed clent_id,client_secret,access_token, and refresh_token and I was able to get them manually and stored them in custom settings object but I think Box has limited time setup for access and refresh tokens so for that I need to create a scheduler class which internally calls box api to get refresh tokens and store them into custom_settings. 
Here is the approach I called a scheduler runs for 10 mins but as soon as run first time the job scheduled for 1 hour, so after I googled I came to know that SF uses per hour so I crreated 6 jobs for running but still no use, please see the below code.

Note: to crate first job I called the following line manually from Ananymous window
System.schedule('BoxRefreshTokensJob 00', '0 0 * * * ?', new BoxAuthRefreshTokensScheduler());
Apex Scheduler class
global class BoxAuthRefreshTokensScheduler implements Schedulable{
    global void execute(SchedulableContext SC) {
        updateBoxCustomSetting();
        System.schedule('BoxRefreshTokensJob 00', '0 0 * * * ?', new BoxAuthRefreshTokensScheduler());
        System.schedule('BoxRefreshTokensJob 10', '0 10 * * * ?', new BoxAuthRefreshTokensScheduler());
        System.schedule('BoxRefreshTokensJob 20', '0 20 * * * ?', new BoxAuthRefreshTokensScheduler());
        System.schedule('BoxRefreshTokensJob 30', '0 30 * * * ?', new BoxAuthRefreshTokensScheduler());
        System.schedule('BoxRefreshTokensJob 40', '0 40 * * * ?', new BoxAuthRefreshTokensScheduler());
        System.schedule('BoxRefreshTokensJob 50', '0 50 * * * ?', new BoxAuthRefreshTokensScheduler());
        
    }
    
    global void updateBoxCustomSetting(){
        try{
            List<Cust_Sett__c> bx=[SELECT id,Access_Token__c, Refresh_Token__c FROM Cust_Sett__c 
                                                    where name='MyCustSett' limit 1] ;
            BoxApiConnection api;
            if (api==null){
            	api = new BoxApiConnection(bx[0].client_id__c, bx[0].Client_secret__c, bx[0].Access_Token__c, bx[0].Refresh_Token__c);    
            }
            api.refresh();
            bx[0].Access_Token__c=api.getAccessToken();
            bx[0].Refresh_Token__c=api.getRefreshToken();
            update bx[0];
            
        }catch(exception e){
            system.debug('*********Exception while updating custom setting:'+e.getmessage());
        }
    }
}

 
Hi,

Working on replacement of standard Notes & Attachments, for this Created a custom attachment object which has fileName, filedownloadLink, etc
and created a VF page which uploads file 
and controller to upload process to BOX and returns the download URL (its too big) and inserts custom attachment object  with that information
and as soon as uploaded, the current page loads with the created new attachment record with download link.

Here I was not able to insert attachment since the following error is throwing.
Attachment Creation Error Insert failed. First exception on row 0; first error: STRING_TOO_LONG, BoxDownloadUrl: data value too large:
BoxAttachment__c obj = new BoxAttachment__c();
obj.FileName__c = fileName; // this text field
obj.BoxDownloadUrl__c = fileDownloadURL; // this URL field 
obj insert;
I think URL field doesn't allows morethan 255 chars, is there any alternate way to have a download link to a field? 

 
Hi,

I have trying to do box integration with all approaches but nothinkg solved. The following approach seems to be easy but still not able to make call to box..
Basically we are trying this integration with Salesforce Box SDK Api (directly installed in salesforce platform) and trying to connect to box and get file Info (but actually we need upload and download, this SDK api has those methods to do that). Please find any clue on that issue and let me know. please look at this steps I followed

Step1: created box app for client id and client secret
2: got Access Token and Refresh Token using postman service
3. used these in following Apex code.
4. when I tried to Attach a file I get the following error.
 
Error:
19:36:28:488 USER_DEBUG [22]|DEBUG| Exception $$$$$$ An unexpected error occurred when trying to make a callout to the Box API. Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.box.com/oauth2/token

And the Apex code is...
 
public class BoxIntegrationClass{
    private static String CLIENT_ID='xxxxxx';
    private static String CLIENT_SECRET='yyyyy';
    private static String ACCESS_TOKEN='yyyyy';
    private static String REFRESH_TOKEN='yyyyy';
    @future (callout=true)
    public static void createAttachment(id attachmentid){
        System.debug('In Integration class  ');        
        BoxApiConnection api = new BoxApiConnection(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN,REFRESH_TOKEN); //This is successfully executed
        System.debug('api ---- '+api); 
        Attachment myAttachment=[select name,body,parentid from attachment where id=:attachmentid];
        BoxFile file = new BoxFile(api, '034192123421'); //This is failing, the error is above 
        try{
        	String previewLink = file.getPreviewLink();
        	System.debug('file link '+previewLink); 
        }catch(Exception e){
            System.debug(' Exception $$$$$$ '+e.getMessage());
        }
    }
}
I don't understand why its failing... please help on this.

 
Hi, 
We have custom attachment which attach the files to BOX (using REST API) and rendering attachment from there when the user clicks on "View" link. But the following functionolity works on PDF and image files, they are directly opening on next tab/window but when we click on Docs or CSV, the file is downloading direclty rather opening  on new page. Please someone give me clues on this? see the following code snippet.
Apex Code: 
public String fileOpen(){
     HttpRequest req = new HttpRequest();
     req.setEndpoint(fileDownloadURL);
     req.setMethod('GET');
     Http binding = new Http();
     HttpResponse res = binding.send(req);
     Blob boxFile = res.getBodyAsBlob();
     String boxResponse = 'data:'+res.getHeader('Content-Type')+';base64,'+EncodingUtil.base64Encode(boxFile );
     return boxResponse ;
}
VisualForce Page:
<apex:page controller="BoxController" action="{!fileOpen}">
    <apex:form >
        <apex:outputText escape="false" value="{!boxResponse}"/> 
    </apex:form>
</apex:page>

Please help me on rendering doc/csv files on page rather downloading.. 

Appreciate your help..
Sumant K
 
Hi,

I'm trying to open/download a file returned from box.

when we click on a "Cleck Me" link, it calls the VF page and calls the Apex .. but I'm not sure how to open/download page from apex
Image and code are below.

User-added image

VF page:
<apex:page controller="BoxController" action="{!fileOpen}">

</apex:page>

Apex code:
 
try{
            String bFileId=String.valueof(ApexPages.CurrentPage().getparameters().get('bFileID'));

            String aToken = api.getAccessToken();
            if(bFileId!=null && bFileId!=''){
                String endPointURLToViewFile='https://api.box.com/2.0/files/'+bFileId+'/content';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endPointURLToViewFile);
                req.setMethod('GET');
                req.setHeader('Authorization', 'Bearer ' + aToken);
                req.setHeader('Content-Type','application/json');
                req.setHeader('Accept','application/json');
                req.setTimeout(120000);
                Http http = new Http();
                HTTPResponse res = http.send(req);
                
                String downloadURL=res.getHeader('Location');

            }
        }catch (Exception e){
            System.debug(' **** File Download Exceptions '+e);
        }
    }

Here I can get "downloadURL" but I don't know how to call this URL to opan/download with that URL.
Could someone please help me on this? 

Thanks,
Sumant K
 
Hi,

I have trying to do box integration with all approaches but nothinkg solved. The following approach seems to be easy but still not able to make call to box..
Basically we are trying this integration with Salesforce Box SDK Api (directly installed in salesforce platform) and trying to connect to box and get file Info (but actually we need upload and download, this SDK api has those methods to do that). Please find any clue on that issue and let me know. please look at this steps I followed

Step1: created box app for client id and client secret
2: got Access Token and Refresh Token using postman service
3. used these in following Apex code.
4. when I tried to Attach a file I get the following error.
 
Error:
19:36:28:488 USER_DEBUG [22]|DEBUG| Exception $$$$$$ An unexpected error occurred when trying to make a callout to the Box API. Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.box.com/oauth2/token

And the Apex code is...
 
public class BoxIntegrationClass{
    private static String CLIENT_ID='xxxxxx';
    private static String CLIENT_SECRET='yyyyy';
    private static String ACCESS_TOKEN='yyyyy';
    private static String REFRESH_TOKEN='yyyyy';
    @future (callout=true)
    public static void createAttachment(id attachmentid){
        System.debug('In Integration class  ');        
        BoxApiConnection api = new BoxApiConnection(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN,REFRESH_TOKEN); //This is successfully executed
        System.debug('api ---- '+api); 
        Attachment myAttachment=[select name,body,parentid from attachment where id=:attachmentid];
        BoxFile file = new BoxFile(api, '034192123421'); //This is failing, the error is above 
        try{
        	String previewLink = file.getPreviewLink();
        	System.debug('file link '+previewLink); 
        }catch(Exception e){
            System.debug(' Exception $$$$$$ '+e.getMessage());
        }
    }
}
I don't understand why its failing... please help on this.