How can i extract attachments from salesforce? - salesforce

I need to extract attatchments out of salesforce? I need to transfer some notes and attachments into another environmant. I am able to extract the notes but not sure how to go about extracting the attatchments
Thanks
Prady

This mostly depends on what tools/utilities you use to extract. The SOQL for Attachment sObject will always return one row at a time if Body field is included in the query. This is enforced to conserver resources and prevent overbearing SOQL scripts.
Approach #1, if queryMore is not available: Issue a SOQL without Body field to enumerate all attachments, then issue one SOQL per attachment ID to retrieve Body
Approach #2: Issue a SOQL to retrieve all needed attachments then loop using queryMore to get them one at a time.
Approach #3: If you can "freeze" the SF environment and just want to take snapshot of the system to pre-load a different one to be used going forward you can use "data exports". In setup menu, in data management there is an export data command, make sure you click "Include in export" to include all binary data. After due process it will give you a complete data backup you can crunch offline.
Btw, body is base64 encoded, you'll need to decode it to get the actual binary

Here is the solution I've used to get the attachment binary content from SalesForce. The example in their documentation points the following:
curl
https://na1.salesforce.com/services/data/v20.0/sobjects/Document/015D0000000NdJOIA0/body
-H "Authorization: Bearer token"
So there are a couple different elements here. The host (https://na1.salesforce.com) you should be able to get after the login process, this host is session based so it can always change. Second element is the rest of the URL, that you will get from the "body" field of the Attachment object. Third and last element is the Authorization header, which is composed by the string "Bearer ", plus the token that is given to you after you authenticate with the SF backend.
The response is the binary file, it is NOT in base64, just save it to a file and you are good to go.
Here is an example of how I did it in Objective C:
// How to get the correct host, since that is configured after the login.
NSURL * host = [[[[SFRestAPI sharedInstance] coordinator] credentials] instanceUrl];
// The field Body contains the partial URL to get the file content
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", [host absoluteString], {AttachmentObject}.body]];
// Creating the Authorization header. Important to add the "Bearer " before the token
NSString *authHeader = [NSString stringWithFormat:#"Bearer %#",[[[[SFRestAPI sharedInstance] coordinator] credentials] accessToken]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
[urlRequest addValue:authHeader forHTTPHeaderField:#"Authorization"];
[urlRequest setHTTPMethod:#"GET"];
urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
Hope it helps.

You can use SOQl Query options, or if you are looking for some automation tool that will help you with quick export, then you can try AppExchange App Satrang Mass File Download - https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EcsAOUAZ&tab=e
Disclaimer: I work at Satrang Technologies, the publisher of this Mass File Download AppExchange App.

In SalesForce attachment will be against an Object for e.g. Account object.
Steps to retrieve attachment (in Java)
Get the ID of the Object to which a file is attached. e.q. Account Object
String pid = Account__r().getId();
Execute a Query on Salesforce Object "Attachment" for the ID in Step 1
*String q = "Select Name, Body, ContentType from Attachment
where ParentId = '" + pid + "'";
QueryResult qr = connection.query(q);
SObject[] sarr = qr.getRecords();*
SObject so = sarr[0];
Typecast Salesforce Generic Object (SObject) to "Attachment" object
*Attachment att = (Attachment)so;*
Retrieve the Byte Array Stream from Body of Attachment, and do the operation needed on byte array.
*byte[] bName = att.getBody();
// Do your operation in byte array stream*

Related

Is there any way to get content of the ZenDesk Attachments instead of redirect URL?

I need to get ZenDesk ticket attachment content like encoded format. ZenDesk API provided only the content url. By using that content url I can only able to get the redirect page of that file. But I need to automate a process that file as Base64 encoded format. Thanks in advance.
Note : I tried to migrate ZenDesk to Salesforce via Dell Boomi.
I found a resolution for my problem and I guess it's the same as yours.
In salesforce apex code I got the url response from zendesk and I used subtring method to get URL of attachment.
After that I used Pagereferece to open the URL, see below:
String exampleMyResponse= '<html><body>You are being <a href="https://xxx.zdusercontent.com/attachment/000001/sdlfkashdf98709udfah?token=eyJhbGciOiJkaX46SgYrFzTEpYqUIzpQeNnl5BMBNoRnUOsgQj389Ei7nNcGOcfGYaavlqLL2qaIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..U8oX8QnYBM1lZMb6rhQGRA.NC3Z9kHC9ZE6HhygIHHan6xWYvoPqziVx76CZ6vcNYHBuAjV-LmBclVJYumKWKXA_PDhXX27z977XKYrLJZSc85a6lJTEqd-V2mP7U6O6r0_6E9hO8CWaA1dyxYYWw8kUsgMFUaPr0wCupxm3NbDzT03ZwO6EBJj79x4UZdauiXfEUrSwdl1pPahlQE2VfFo8DprgX9GQHzRFm5lwMrhA3crogo8Ox';
**//You need to authorize your domain "https://xxx.zdusercontent.com"** in remote site
Pagereference pg = new Pagereference(exampleMyResponse.substringAfter('href="'));
**Blob b = pg.getContentAsPDF();**//Here you can use getContent() too for another type of file
//Example to save PDF
Attachment att = new Attachment(Name = 'stvm_4', Body = b, ContentType = 'application/pdf', ParentId='Sobject_Id');
insert att;

Dynamic named credentials Salesforce

I need to update the permissions of a Drive document from Salesforce.
I wanted to use Named Credentials, but I didn't find any way of building a call like this one:
https://www.googleapis.com/drive/v3/files/{documentId}/permissions
where {documentId} is a dynamic value.
I've seen that it is possible to add a prefix, but actually even if I create a Named Credential with only https://www.googleapis.com/drive/v3/files, when I call it from my Apex class I get a permission error.
Is there a way to achieve what I would like or I need to change approach?
Thank you
What exactly error are you getting? Salesforce security about not having access to class X? Something about callouts not allowed from triggers? You're sure it works with hardcoded document id?
Should be possible to make the named credential point to https://www.googleapis.com or https://www.googleapis.com/drive/v3/files/ and then add the rest of the endpoint in Apex. If it throws errors - maybe Drive's API is special, you'd need to read up.
String endpoint = 'callout:MyNamedCredential' + '/abc123/permissions';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
I have something like that:
Named credential pointing to https://maps.googleapis.com/maps/api/geocode/json
and then
static final String ENDPOINT = 'callout:GoogleMaps?key={0}&latlng={1}&result_type=premise%7Cstreet_address';
String apiKey = SomeCustomSetting__c.getInstance().GoogleApiKey__c;
String latLng = '60.23,11.17';
req.setEndpoint(String.format(ENDPOINT, new List<String>{apiKey, latLng}));
HttpResponse res = h.send(req);
You could also look into "Files Connect" API I guess.

Where to store a Authorization Bearer Token in Salesforce?

We have an external vendor that requires us to include a bearer token in the http request header when we communicate with the API. This token shouldn't be left in the code unencrypted so where is the best place to store it? The Named Credential type doesn't seem to support storing a simple token and the Custom Setting option seems overly complicated and unnecessary. This is a single token string that will be used for every API call regardless of which user. I have searched high and low on google and haven't found an obvious solution that works.
There are some options but they're limited for your code as end user. A determined developer/sysadmin will learn the value eventually.
If you'd build a managed package you could use a protected custom setting (managed package's code could see it but not the client code, even sysadmins)
Check some of these:
https://developer.salesforce.com/page/Secure_Coding_Storing_Secrets
https://salesforce.stackexchange.com/questions/226110/what-is-the-best-way-of-storing-username-and-password-in-salesforce
https://salesforce.stackexchange.com/questions/478/using-transient-keyword-to-store-password-in-hierarchy-custom-setting
https://salesforce.stackexchange.com/questions/55008/is-encrypting-passwords-in-protected-custom-settings-a-security-requirement
You could make a custom setting with 2 text fields, 1 with encryption key and 1 with encrypted value in it. Look at Crypto class.
Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);
Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);
Your initialisation vector could be org's id or something else that's easy to access and unlikely to change (I don't know if your vendor's API has test and prod endpoints but it's an added bonus that after sandbox refresh this will fail to decrypt OK until you change the custom setting... you wouldn't want to send test messages to production API), you'd generate key once & store it in setting.

Sending attachments as an email from a form - NOT from local files

I have created a HTML email form which allows a user to enter To, subject, message, content and attachments however I cannot get the attachments to send.
I have researched online and came across many variations of this code:
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
But is there a way of sending attachments input into the form instead of adding the file path to a file in the code?
Thanks
First, the files need to be uploaded from the browser to the server using the html form. Depending on what you're using to manage the uploaded data, you can store the file data in memory or in files on the server. If you store it in memory, you can use a ByteArrayDataSource instead of FileDataSource in your code above.

How can I convert a file received as blob in HttpResponse call to an audio file in Salesforce Apex coding?

I am actually trying to implement text-to-speech conversion in Salesforce by hitting a third-party api. When i send the request through Postman, i get back the proper response in .wav format. However, I'm not being able to handle this reponse programatically in salesforce end, as I am not able to store the response in any audio object.
Any assistance would be greatly appreciated.
Thanks in advance.
Abhishek.
Not 100% sure of what your trying to do but it would look something like this assuming you built your object correctly
ResponseObject result = new ResponseObject();
result = (InnerClasses.ResponseObject)JSON.deserialize(json, InnerClasses.ResponseObject.class);
This is supported by IBM's Watson Salesforce SDK, available here
The functional tests for Watson's text-to-speech services can be found here refer to the method
testSynthesize(String username, String password, String customizationId)
The audio file returned as part of the response could be saved as an attachment in Salesforce by simply creating it from the IBMWatsonFile like on this example,
IBMWatsonFile resp = textToSpeech.synthesize(options);
Attachment attachment = new Attachment();
attachment.Body = resp.body();
attachment.Name = resp.name();
attachment.ParentId = '<your salesforce parent id>';
insert attachment;
This code uses basically the method getBodyAsBlob() available from the HttpResponse class
before using this approach, please consider the governor limits enforced by Salesforce on any APEX callout, refer to the Maximum size of callout request or response documented here

Resources