Custom button: How to pass currency field to an Apex web service?


you can try using the VALUE function to get the decimal value from the currency field before passing it to the webservice method.
Example:
We want to pass decimal value of Opportunity Amount. Then we use below code in custom button to pass decimal value to web-service.
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}

var amt = {!VALUE(TEXT(Opportunity.Amount))};
var retVal = sforce.apex.execute("WSclassname", "WSmethod", {oppAmt:amt});
alert (retVal) ;
window.location.reload() ;

Share certain records with only certain users


If you would require to have some records to only be shared with certain users, e.g. based on record level, to a certain group (those selected users), and the rest of the records (e.g. records that are the other recod types) with the rest of the internal users.

It can be done by restricting all objects on OWD(Organization-Wide Defaults) level to private and then share certain records.By default 'Grant Access Using Hierarchies' is selected (checked). If you don't want to share the records with users based on role hierarchy, make sure to uncheck this box for respective objects in OWD settings.

Once the OWD setting for an object is set to Private, applying Sharing rules based on criteria would be the best way to meet your requirement scope.If you want Users to share at record level, you can also enable Manual Sharing.

You can navigate to OWD by searching Sharing settings in Setup > quick search.

You can refer Below link for more sharing Information.
https://developer.salesforce.com/docs/atlas.en-us.securityImplGuide.meta/securityImplGuide/security_data_access.htm

Reset changed user profile permissions

Hi,

There is no way to "Reset" the changes made on your profile.

But there is one way by which you can revert it some what.

you can

look in to the "View Setup Audit Trail" from Setup and see the list of changes made to your profile, and then try to correct it manually.


Hope this helps.

Merge field syntax is correct yet the generated PDF document is not displaying the data : Steelbrick CPQ


This might be because of merge field is not populated on source code. So try to verify your merge field in source code.

If your merge field syntax is correct yet the generated PDF document is not displaying the data or is displaying an error, click the HTML button highlighted below in your template content toolbar to troubleshoot.

Ensure your merge field name was pasted in correctly. Formatting tags can get inserted within the brackets when pasted in from a rich text applications.
Instead, paste from Notepad, which strips out all excess formatting.

Alternatively, click the HTML button on the template content editing toolbar and remove formatting tags manually, making sure that the merge field syntax is not interrupted by these tags.

If still not working click Source Button and check if merge field is populated.


For merge field information visit: https://community.steelbrick.com/t5/Quote-Templates-Knowledge-Base/Merge-Fields/ta-p/299

Custom Picklist lookup using javascript in Visual page

In this post I'm gonna show you how to create simple custom picklist lookup in Visual page using javascript.

We will use window eventlistner to get data from child window open by parent window.

Here is snippet of my simple vf page.

  
<apex:page >
    <script>
        function open_pop_up(idx, field, sObj){
            var child = window.open('/apex/picklistLookup?idx='+idx+'&field='+field+
'&sObj='+sObj+'', '_blank', 
'toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400')
            console.log('==> Child: ' + child);
        }
        
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
        //Listen to message from child window
        eventer(messageEvent,function(e) {
            console.log('parent received message!: ',e.data);
            var dataArr = e.data.split(':'); 
            var elmtId = e.data.substring(0, e.data.lastIndexOf(':'));
            var datavalue = e.data.substring(e.data.lastIndexOf(':') + 1,e.data.length);
            document.getElementById(elmtId).value = datavalue;
        },false);  
        
    </script>
    
    <input id="testId" value="" onclick="open_pop_up('testId','CustomerPriority__c',
'Account');"/>
</apex:page>

Let me explain the code.

when we click on input it will open popup lookup window.
Here i have use my custom picklist field CustomerPriority__c of Account Object for test data.

Now new vf page for lookup popup window.

  
<apex:page controller="PicklistLookupCon" showHeader="false">

    <apex:variable value="{!0}" var="rowNum"/>
    
    <table>
        <tr>  
            <td></td>  
            <td>
                <input type="button" value="Insert Selected" onclick="InsertSelected()" class="btn"/>
            </td>
        </tr>
        <apex:repeat value="{!picklistValues}" var="plv">
            <tr>
                <td>
                    <input type="checkbox" onclick="selectValue('{!rowNum}', this.checked, '{!plv}')"/>
                </td>
                <td>{!plv}</td>
            </tr>
            <apex:variable value="{!rowNum+1}" var="rowNum"/>             
        </apex:repeat>            
    </table>
    
    <script type="text/javascript">
        var arrValue  = new Array();
               
        function selectValue(id, isChecked, value){

            if(isChecked == true){
                arrValue[arrValue.length] = value;
            }else{
                var index = arrValue.indexOf(value);
                arrValue.splice(index,1);
           }  
        }
           
        function InsertSelected(){
            console.log(window.parent.opener);
            var win = window.parent.opener;
            var dataStr= '';
            
            for(var k=0;k<arrValue.length;k++){
                if(k==0) dataStr = arrValue[k];
                else dataStr +=','+arrValue[k];
            }
            win.postMessage('{!$CurrentPage.parameters.idx}:'+dataStr, window.parent.opener.location.href); 
            window.parent.close();
        }
  </script> 
</apex:page>

controller:

public without sharing class PicklistLookupCon {

    string sObj = Apexpages.currentpage().getParameters().get('sObj');
    string field = Apexpages.currentpage().getParameters().get('field');

    public picklistLookupCon(){
    
    }
        
    public List picklistValues{
      get{
          if(picklistValues!=null)
              return picklistValues;
          else{
              picklistValues = new List();
              
              Map gd = Schema.getGlobalDescribe(); 
              Schema.SObjectType ctype = gd.get(sObj);
              Map fmap = ctype.getDescribe().fields.getMap();
              Schema.DescribeFieldResult fieldResult = fmap.get(field).getDescribe();
              List ple = fieldResult.getPicklistValues();   
              
              for( Schema.PicklistEntry f : ple){
                  picklistValues.add(f.getValue());
             }
          }
          return picklistValues;
      }
      set;
    }
    
 }

That's it.

Yepppieee you done it.

Simple Alexa skill in Node.js using Heroku as hosting server

The think which we gonna need is;
1. Heroku login
2. Git respository
3. Amazon developer account

We will use command promt for developing node js code and deploying it to heroku.

Here are the links for download CLI for heroku and gitHub/
GitHub: https://git-scm.com/download/
Heroku cli: https://devcenter.heroku.com/articles/heroku-cli

First of all create a new directory in local machine name it whatever you like, i have given name sample. Similar create a new repository in your git account.you will below screen:




Go through the given step for creating a new respository on the command line

for using alexa we will use alexa-app-server library.

for using node js you will need node js to be install so first install npm to your local machine.
https://nodejs.org/en/download/

For installing alexa-app-server type:

npm install alexa-app-server

after finishing installing alexa-app-server lib, Create a file server.js and copy paste below code in it.

'use strict';

var AlexaServer = require( 'alexa-app-server' );

var server = new AlexaServer( {
 httpsEnabled: false,
 port: process.env.PORT || 80
} );

server.start();

Let me explain what does code means.

Here we have set port to be used by server. if code is running from heroku than it will use  port given by heroku by (process.env.PORT) other wise port 80 will be use.

Now we will create Procfile. this will tell heroku what to do when process will run.file name should be without extension. just use Procfile.

web: node server.js

Now will create Package.json file by tying npm init
this will ask some question and after completing that json file will get created.

After that push your file to git by performing below command.

git add .
git commit -m "added procfile and server.js"
git push origin master

Now, create new folder in main folder named apps and in that create sub folder skills  where add file for our skills.create new Github repository for skills name it whatever you like i use sampleskills.
perform similar step of initiaze repo and do the initial commit/push.Now we will indicate github that apps/skills is submodule. To do this go to main folder and type

git submodule add https://github.com/rsanjuseason/sampleskills.git apps/skills

Replace https://github.com/rsanjuseason/sampleskills.git with your skill git link.

Now we will generate package.json for skills folder.so that npm can know that it submodule.
To do this run below command:

npm init

Now we will install alexa-app package.

npm install alexa-app

Now again regenerate package.json for install dependency.

Now it's time to create index.js file for performing something by skill, something like say hello world.

module.change_code = 1;
'use strict';

var alexa = require( 'alexa-app' );
var app = new alexa.app( 'myskill' );


app.launch( function( request, response ) {
        response.say( 'Welcome to Alexa World' ).reprompt( 'Ask Something.' ).shouldEndSession( false );
} );


app.error = function( exception, request, response ) {
 response.say( 'Sorry some error occured ' + error.message);
};

app.intent('sayHello',
  {
 "utterances":[ 
  "say Hello",
  "Hello alexa",
  "What's up",
  "Hey alexa"]
  },
  function(request,response) {
    response.say("Hello, Welcome to alexa world.");
  }
);

module.exports = app;


To test our code run below command in cmd from main folder:

node server.js

Then, open browser and open below link:

localhost/alexa/myskill



Hope this works, then we will deploy it heroku so, that it can invoke from any place.

So, now we will commit our work to git.
first commit/push skill files to git.move to skill directory and type:

git add .
git commit -m "skills file index.js"
git push origin master


then we will push out main folder files to git by below commands after moving to main directory:

git submodule forech git pull origin master
git add .
git commit -m "update submodule"
git push origin master

Now create New app in heroku to deploy our files.Mine is helloworldskill

after creating app type below command

heroku login

After this you have enter your login details then,

heroku git:remote -a helloworldskill

Replace helloworldskill  with your app name.then push your file.

git push heroku master


Now its time create skill on amazon.go to your developer amazon and create a new skill



Add intent schema and utterences.


In configuration tab select Https and below url 

https://helloworldskill.herokuapp.com/alexa/myskill

Replace https://helloworldskill.herokuapp.com with your heroku app url.



In SSL Certificate select

My development endpoint is a sub-domain of a domain that has a wildcard certificate from a certificate authority

Now its time test our skill, enter utterance it should work fine.



You can test it in simulator or echo dot.
Here is link for simulator

https://echosim.io

Just Say

"alexa, Ask helloworld to say hello"

it will repeat back with

"Hello, welcome to alexa world"

Yehhhh, we have created our first alexa skill.

Hope this helps
Thanks.







Simple Status Loader with simple Html salesforce

A simple status loader image can be easily done using simple html div tag.

Here is code snippet for it.

<div id="loading" style="display:none;">
  <div style="width: 100%; height:100%; background:#000; opacity: 0.4; top:0px; left:0px; 
      position: fixed; z-index:1000000;"></div>
     <div class="dv_load" style="position:fixed;top:40%;left:50%;z-index:1000000">
        <img src="/img/loading24.gif" style="vertical-align:middle;" />
        <span>Loading...</span>
      </div>
</div>

you can load is just by changing its display property that is display:none to block.

function startProcess() {
   document.getElementById("loading").style.display = 'block';
}
    
function endProcess() {
    document.getElementById("loading").style.display = 'none';
}

function startprocess for loading image and stopprocess for stop i.e to hide.

If have any questions, you can as in comment.

Thanks.
Have happy coding.



Auto generate password apex salesforce.

To generate random password you can use crypto class for generating password in apex.

crypto class will generate random blob. Use can use that blob for creating String.
use trim string to whatever length.

Here is Sample class for generating password:

public class PasswordGenerator {
public static String getPassword(Integer passlength) {
Blob blobKey = crypto.generateAesKey(128); String key = EncodingUtil.convertToHex(blobKey); System.debug(key);
return key.substring(0,passlength); } }

How to put a static image in a flow designer ?


The Rich text editor on the screen element currently does not support img src tags.
However, the flow run-time interprets any text as HTML. So, you could store the html markup in a custom setting or any database record, fetch it in a variable and use that in the screen.

You can display document image in flow Designer by creating text variable.


Create Variable of type text in flow Designer.

Data Type: text
Input/output type :  Output only
Default value:   
<img src="https://Domain_url/servlet/servlet.FileDownload?file=Your_documentid&oid=Org_id" width="100px" Height="100px"/>

Note: Domain_url  >>>  set your domain url
           Your_documentid >> set your document id.
          Org_id >>> set your org id

You can get your Org id by Navigate to Administration Setup > Company Setup> Company Information.

you will find org id at Salesforce.com Organization ID field.

Now use this newly created variable in Screen.

Resize an image before upload using JQuery.



function handlePhoto(evt)
{
var file = evt.target.files[0];
var FR = new FileReader();           
var img = new Image();
var can = document.createElement("canvas");
var ctx = can.getContext('2d');
FR.onload = function(e) {
img.src = = e.target.result;
img.onload = function() {      
var ctx = can.getContext('2d');
//Set canvas 
var max_size = 750,// pull max size from a site config
width = this.width,
height = this.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
can.width = width;
can.height = height;
ctx.drawImage(this, 0, 0,width,height);
var dataURI = can.toDataURL(); 
dataURI = dataURI.replace(/^data:image\/(png|jpg);base64,/, "");
        console.log('New Image source: ' + dataURI);                         
}
};       
FR.readAsDataURL( this.files[0] );
}

Http Request with multipart/form-data Salesforce upload file.



public void upload(String boundary,string filename,boolean file_body) {


    String header = '--' + boundary + '\r\n' +
                        + 'Content-Type: application/octet-stream\r\n'+
                        + 'Content-Disposition: form-data; name="file";filename="' + filename +'"';

        String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header + '\r\n\r\n'));

        String footer = '--' + boundary + '--';

        while(headerEncoded.endsWith('='))
        {
            header += ' ';
            headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
        }

        String bodyEncoded = EncodingUtil.base64Encode(file_body);
       
        Blob bodyBlob = null;

        String last4Bytes = fileContent.substring(bodyEncoded.length()-4,bodyEncoded.length());
        System.debug('----->last4Bytes: '  + last4Bytes );

        if(last4Bytes.endsWith('==')) {
            last4Bytes = last4Bytes.substring(0,2) + '0K';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the \r\n to the Blob, so leave footer as it is.
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        } else if(last4Bytes.endsWith('=')) {
            last4Bytes = last4Bytes.substring(0,3) + 'N';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the CR e.g. \r, still need to prepend the line feed to the footer
            footer = '\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);            

        } else {
            // Prepend the CR LF to the footer
            footer = '\r\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        }

        System.debug('---> Body: ' + bodyBlob);
        HTTPRequest req= new HttpRequest();
        req.setendpoint('https://upload.box.com/api/2.0/files/content');
        req.setmethod('POST');
        req.setHeader('Authorization','Bearer ' + creds.Access_Token__c);
        req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
        req.setBodyAsBlob(bodyBlob);
        System.debug(' res -----> :' + req.getBody());
        Http p = new Http();
        HttpResponse res= new HttpResponse();
        res = p.send( Req );

}


Creadit to: http://blog.enree.co/2013/01/salesforce-apex-post-mutipartform-data.html

Set div at center of the screen CSS.

If you know the dimensions of div.

.centered {
  position: fixed;  /*IE6 position:absolute */
  top: 50%;
  left: 50%;
  margin-top: -50px; /* Half of the Height of div*/
  margin-left: -100px; /* Half of the Width of div*/
}

If you Don't know the dimensions of div.

.centered {
  position: fixed; /*IE6 position:absolute */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

System.LimitException: DML currently not allowed


System.LimitException: DML currently not allowed VisualForce.


This Error because of allowDML is false for VisulaForce Component.

Resolution: Set allowDML="true" in component. 

Difference between angular.copy() and assignment (=).

$cope.context = 'some text';
$scope.master = context;
Thus in the later case, if you we're to change something in $scope.master you would also change context.
But in $scope.master = angular.copy($scope.context);
 angular.copy() performs a deep copy of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.
For more details on angular.copy visit Here.
     

Methods defined as TestMethod do not support Web service callouts Stack Trace: null


This error occurs because webService callouts is not allowed in Test class.

To bypass callouts add HttpcalloutMock class.



Here is Sample test class with mock class to bypass webservice Callout.

**********************  Test Class ***************************

@isTest 
private class Test_class {

    private class RestMock implements HttpCalloutMock {
        
        public HTTPResponse respond(HTTPRequest req) {
            String fullJson = 'your Json Response';
            
            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    }
    static testMethod void service_call() {
        
        Test.setMock(HttpCalloutMock.class, new RestMock());
        Test.startTest();

        //your webserive call code

        Test.StopTest();


    }
}



Mock class will take care webservice callouts.





How To Call Function after ng-repeat get Load ?



<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
 <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script>
               var App = angular.module('myApp', ['ui.bootstrap']);
                App.directive("repeatEnd", function(){
                    return {
                        restrict: "A",
                        link: function (scope, element, attrs) {
                            if (scope.$last) {
                                scope.$eval(attrs.repeatEnd);
                            }
                        }
                    };
                });

           App.controller('myctrl',['$scope',function($scope)
            {

                     $scope.names = '["test","Tst2"]';
                      var onEnd = function(){
                             console.log('load is complete');
                      };

            }]);
</script>

<body ng-app="myApp" class="container" ng-controller="myctrl" id="LineSite">
        <div ng-repeat="name in names" repeat-end="onEnd()"/>
</body>


Creating new document from image base64 text

Creating new document from image base64 text


        blob fileContent = EncodingUtil.base64Decode(fileData); //fileData is base64 data of image. 
  Attachment a = new Attachment(parentId = parentId); // parentId : Id of record.
  a.body = fileContent;
  a.name = 'ImageName.png';
  insert a;

Avoid Recursive Trigger

public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}