Tuesday, March 26, 2019

Blob(Img/Doc) in HTTP Post request with Text Param or without text

Since rest integration is commonly used with Post request. 
When we do post request with only Text Param then it's simple to pass Text Param in Body in requested format. 

In some scenarios we may need to pass Blob(Img/Doc) with Text param or without Text param. 

Following are the key point for Blob(Img/Doc) in HTTP Post request with Text param or without text. 

1. Encoding : The Blob body should be encoded with following approach.

                       EncodingUtil.base64Encode(doc.Body)

2. Content Type in Header : Content type format should be in following format 
   
                       req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

3. Boundary : The boundary parameter is set to a number of hyphens plus a random string at the end, but you can set it to anything at all. The problem is, if the boundary string shows up in the request data, it will be treated as a boundary.

4. Body : Body as a string is very important in this scenario. So body should be created carefully. 
    
private static final String CRLF = '\r\n';
private static final String CHAR = 'UTF-8';
final String boundary = '---------------JKKJLJLJLJLJL';


body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="name"')+(CRLF);
body+=('Content-Type: application/json; charset=' + CHAR)+(CRLF);
body+=(CRLF);
body+='{"Text Param":{"Text Param Value"}}'+(CRLF);
/* if Text param is not needed this above line can be skipped*/      
body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="file"; filename="' + filename + '"')
                +(CRLF);
body+=('Content-Type: text/plain')+(CRLF);
body+=(CRLF);
body+=EncodingUtil.base64Encode(doc.Body);

body+=(CRLF); 
        
        
body+=('--')+boundary+('--')+(CRLF);

5. Complete Code


        //specify the enedpoint variable
        String targetURL = 'End Point';
        
        Document doc = [SELECT ContentType,id, Name, body FROM Document WHERE Id = '***************'];
        String fileName = doc.Name;            
        String loginToken ='LoginToken'   
        string body = '';
        final String boundary = '---------------JKKJLJLJLJLJL';   
            
            
        body+=('--')+boundary+(CRLF);
        body+=('Content-Disposition: form-data; name="name"')+(CRLF);
        body+=('Content-Type: application/json; charset=' + CHARSET)+(CRLF);
        body+=(CRLF);
        body+='{"Text Param":{"Text Param Value"}}'+(CRLF);
        
        body+=('--')+boundary+(CRLF);
        body+=('Content-Disposition: form-data; name="file"; filename="' + filename + '"')
                +(CRLF);
        body+=('Content-Type: text/plain')+(CRLF);
        body+=(CRLF);
        body+=EncodingUtil.base64Encode(doc.Body);

        body+=(CRLF); 
        
        
        body+=('--')+boundary+('--')+(CRLF);   
            System.debug('----->'+body);
            
            HttpRequest req = new HttpRequest();
            req.setEndpoint(targetURL);
            req.setHeader('x-auth-token', loginToken);
            req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
            req.setMethod('POST');
            req.setBody(body);
            Http http = new Http();
            HTTPResponse res = http.send(req);
            
            System.debug('**** response '+res.getBody());
            System.debug('**** response '+res.getStatus());


Saturday, May 21, 2016

Custom Objects and their fields from CSV to SF via apex

Generally customers give us a excel sheet for the custom objects and the custom fields. It take too much time to create them manually.
So I have tried a code with the help of meta data api class , which can create all the custom objects and custom fields from CSV to SF in a single click.

There are two standard objects in SF which can be accessed via apex
1. CustomObject
     
MetadataService.MetadataPort service = new MetadataService.MetadataPort();    
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId(); 
        
        List<MetadataService.Metadata> fields = new List<MetadataService.Metadata>();
        
        for(String s : objSet){
            MetadataService.CustomObject customObject = new MetadataService.CustomObject();
            customObject.fullName = s+'__c';
            customObject.label = s;
            customObject.pluralLabel = s+'s';
            customObject.nameField = new MetadataService.CustomField();
            customObject.nameField.type_x = 'Text';
            customObject.nameField.label = 'Name';
            customObject.deploymentStatus = 'Deployed';
            customObject.sharingModel = 'ReadWrite';
            fields.add(customobject);
        }
        List<MetadataService.SaveResult> results = service.createMetadata(fields);



2. CustomFields
      
MetadataService.MetadataPort service = new MetadataService.MetadataPort();   
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId(); 
        
        List<MetadataService.Metadata> fields1 = new List<MetadataService.Metadata>();
        
        for(String s : multField){
           MetadataService.CustomField customField = new MetadataService.CustomField(); 
           customField.fullName = s.substringBefore('-')+'__c.'+s.substringBetween('&')+'__c';
           customField.label = s.substringBetween('&');
           if(s.substringAfter('#') == 'Text'){
               customField.type_x = 'Text';
               customField.length = 42;
           }else if(s.substringAfter('#') == 'Number'){
               customField.type_x = 'Number';
               customField.precision = 18;
               customField.scale = 2;
           }else if(s.substringAfter('#') == 'Checkbox'){
               customField.type_x = 'Checkbox';
               customField.defaultvalue  = 'false';
           }else if(s.substringAfter('#') == 'Email'){
               customField.type_x = 'Email';
           }else if(s.substringAfter('#') == 'Currency'){
               customField.type_x = 'Currency';
               customField.precision = 18;
               customField.scale = 2;
           }
           fields1.add(customField);
        }  
        List<MetadataService.SaveResult> results = service.createMetadata(fields1);


So we need to do following steps.....

A. The sheet should be in a csv format because it returns a string.
   


B. Select the file which you want to create

C. Click Ok to create objects and their related fields.



So if you need the full code or demo then please let me know.


Thanks
Vikas Gaur


Saturday, May 14, 2016

Analog Clock

                                                     "Time is money"

When you are working in any salesforce org then  one thing you have in your mind that is TIME. I will say that current time of the org or current time of login user or particular time zone or GMT. So we have following OOTB in salesforce to get the time

1. System.now();
2. System.today();
3. Time zone of login user based on UserInfo.getUserId()
5. Formula field
6. Workflow
7. Some other also

What if we have a analog clock for the same at home page as following


So I tried to build to an application which will work for this requirement. For now this working based on the GMT. It can be extended for login user or particular time zone. 
We can see working demo on following link

http://vickygaur-developer-edition.ap1.force.com/Demo/AnalogClock

So when we add this link in home page component and page layout , then it will be visible at location.

As always please let me know for suggestions and sample code. 


~Vikas Gaur 
  


Saturday, April 30, 2016

Weather Report And Forecasting In Salesforce

As we know that a weather report can only be given for a past period and gives the actual weather conditions that  already occurred and calculated on the particular time.

So in salesforce it may be an application or customer requirement to get the weather report with forecasting. There may be two scenario where we may need weather report in salesforce.

1. Weather report of login user : -
                                                Salesforce org is the collections of multiple users. So when a user gets login then on home page a section of weather report can be displayed.
This is also possible in community, portal and lightning.


2. Weather report for given city:- 
                                             We can provide a input section where the user will enter the city name and will get the corresponding weather report.

 
So I have tried to implement same kinda in salesforce which has following things

 A. Platform - Salesforce
 B. API - Yahoo
 C. API Type - Rest
 D. Weather Information - Temperature, Humidity, Pressure, Rising, Visibility
 E. Forecasting - For next 10 days 

Demo - http://vickygaur-developer-edition.ap1.force.com/Demo/WeatherChecker

Please let me know for some suggestions and if need of sample code.


Thanks
Vikas Gaur
excellencegaur@gmail.com
9990540382

Wednesday, September 9, 2015

Custom Login

Hello Folks,


I am back to my blog with some interesting thing. Some time we may need to login in salesforce with funky page.  We will use following url

https://login.salesforce.com/?un=username&pw=password

And make redirect it to requested url.


Happy Coding

Thanks
Vikas Gaur

Monday, April 20, 2015

Worldpay Integration

Worldpay is online payment gateway which is used to make online payment. In worldpay there are two types of payments
  1. Oneoff Payment
  2. Recurring Payment

Oneoff Payment means instant payment or single payment. In this type of payment the payment is done at once.

Recurring Payment means multiple payments which can be done weekly , monthly or yearly. This type of payment has certain start date of payment.

When we register with Worldpay we will be given two separate URLs for each method of payment and currency set we will be using. One will be the URL for the Test Environment and the other will be the URL for the Production Environment.
Initially the integration is done with Test Environment. After being successful integration with Test Environment stuff can be copied from Test Enviornment to Production.

To integrate with Worldpay we need to hit following urls



Both urls need certain parameters. Some of them are mandatory and some optional.

Mandatory Parameters:-
1. instId : Your Worldpay Installation ID. This is a unique 6-digit reference number assigned to us. It tells us which payment methods and currencies your installation supports.
  1. cartId : A reference we assign to help us identify the purchase.
  2. Amount : The total cost of the purchase.
  3. Currency : The purchase currency
  4. testMode : 100 for Test Enviornment/0 for Production
After redirecting on Worldpay we will see the following screen

From here we can select any card type and will process for payment. After a successful payment a response is generated which can be used to trigger in our system after writing a server side script.

The redirection from Worldpay may be customize. It means after a successful payment if we wish that shopper may be redirected to our website.
To make redirection at requested url resultY and resultC files are used whose code may be customized. ResultY is for successful payment and resultC is for cancelled payment.
We can add our own details to the result page, in order to individualise each transaction. For example, we can add the shopper’s name, the product description and the cost.

Payment Response Message:-

We can set up and use the Payment Response messages feature, which enables us to automate and control ourwebsite. The Payment Response feature posts the payment information from Worldpay server to a URL on our server securely.




References:-

More details about Worlpay Integration may be get from following urls
If you need any sample apex code you may contact to me at excellencegaur@gmail.com.



~Vikas