Wednesday, March 16, 2016

Generate strong random password in Apex

Hi Coders,

I thought this might be handy so thought of sharing this .

It will create a random password with specified length  

public String generateRandomString(Integer len){
        String randStr = '';
        final String upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        final String numChars = '0123456789';
        final String LowerChars = 'abcdefghijklmnopqrstuvwxyz';
        final String specialChars = '!#$%-_=+<>';
        while (randStr.length() < len) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), upperChars.length());
           randStr += upperChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), numChars.length());
           randStr += numChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), LowerChars.length());
           randStr += LowerChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), specialChars.length());
           randStr += specialChars.substring(idx, idx+1);
        }
        return randStr; 
    }

Happy Coding !!!!!!!!!!!!!!!

Thursday, March 10, 2016

How to terminate AsyncApexJob [EXCEPTION: System.StringException: You can't abort scheduled apex ]

I thought this might be useful to developers. 

EXCEPTION: System.StringException: You can't abort scheduled apex : This exception may happen for 2 reasons
  1. It is not a CronTrigger ID (parent Id) for the Async Apex job 
  2. You are trying to delete a orphan Async Apex job, that is no parent Id.


Second situation is rare but it can happen. In that case you might face problem while deploying  the batch class again. The deployment will fail as the batch is already executing (queued )  for a long time.

If this happens you need to call saleesforce support to clear this. BUT before you call salesforce support please tray this which might help .

  1.  login to "https://workbench.developerforce.com/login.php
  2. On right corner, it will be showing your name and API version. Click on that link
  3. There you will find change API version, change it to 32
  4. Go to Utilities >> Apex Execute
  5. There run this command System.abortjob() with job Id

Please note the API version is very important we can't do this from developer console because we can't change the API version there, alternatively you may choose the version during login as well while logging -in to workbench. I believe this would help you. Please let me know if you have any other questions, I would love to help you in that as well.

Have a Great Day! 


Monday, February 22, 2016

Get Salesforce record ID from lookup field in Visualforce page

Hello Friends,

Recently I was working on a requirement where I have to validate some lookup field on visualforce page itself not in apex without submitting form to server. 

I did lots of research and after having a lots of dig down of salesforce source code I identified each lookup field is associated with one hidden field with a "_lkid" appended to the id this help me to identify the record uniquely 

<apex:page standardController="Contact">
   <apex:form>
      <apex:inputField value="{!Contact.AccountId}" id="accountId onchange="getAccountSFId();">
          <script>
                  var accountId = "{!$Component.accountId}";
          </script>
   </apex:form>
   <script>
           function getAccountSFId(){
              var accId =  accountId + '_lkid';  
              // This will give you the 18 digit SF id of the account and you can do what ever you want with this 
              console.log(document.getElementById(accId ).value);
           }
   </script> 
</apex:page>

Tuesday, December 29, 2015

Change your life

Hello Friends,

MMM global is a community of common people where we help each other to make all our feature better to build a better world for our family & children .

I have found MMM Global is the easiest way for my financial freedom with lots of hesitation & thought I started MMM when I saw one my known friend is doing good .

I have a brief discussion with my friend Raju understand what MMM is how it work how I will be benefited.

Please note MMM is a helping community it is not a earning machinery or stock market or bank where you should join with your spare money as you might loose .

With MMM extra your money can grow up to  1005 per month .

If you want to join us click here  if the link does not  work go to https://mmmglobal.org/?i=sfon  #MMMGlobal #MMMExtra #Bitcoin #news

Friday, December 11, 2015

Dealing with multiple JQUERY load and avoiding conflict with bootstrap

Hello Everyone.

Today I faced CSS and JQUERY confident issue very badly. I have to use JQUERY week calender which run under jquery 1.4 and have to use bootstrap3 now the catch is bootstrap need a higher version of jquery to run .

How i resoled the above problem . after doing lots of research and search in stack overflow I found the solution

1) For JQUERY CONFLICT :

<script src="jquery1" />

<script src="jquery2" />
<script>
jQuery.noConflict();
</script>

Now where ever you are using bootstrap use 


<script>

jQuery(".class").fun();
</scrirt>

2) The CSS conflict . 


Wrap bootstrap CSS with name space .


Click here to see the live demo Here.


like this 


#bootstrap {

  /*!
 * Bootstrap v3.0.0
 *
 * Copyright 2013 Twitter, Inc
 * Licensed under the Apache License v2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Designed and built with all the love in the world by @mdo and @fat.
 */

  /*! normalize.css v2.1.0 | MIT License | git.io/normalize */


}

#bootstrap article,
#bootstrap aside,
#bootstrap details,
#bootstrap figcaption,
#bootstrap figure,
#bootstrap footer,
#bootstrap header,
#bootstrap hgroup,
#bootstrap main,
#bootstrap nav,
#bootstrap section, ....


<div class="content">
    <div id="bootstrap">
        <h1>Header 1</h1>
        <h2>An example of styles using bootstrap.</h2>
        <h3 class="text-muted">It's not pretty, but it works.</h3>
        <a href="#" class="btn btn-primary">Button</a>
        <br></br>
        <p>Notice how the markup in this div is not inheriting from the user's custom CSS.</p>
    </div>
    <hr></hr>
    <div id="Preview">
        <!-- Start Html Template -->
        <style>
            .user > h1 {color: red;}
            .user > h2 {color: blue;}
            .user > h3 {font-size: 40px;}
            .user > .btn {margin-top: 24px; background-color: red;}
        </style>
        <div class="user">
        <h1>Header 1</h1>
        <h2>An example of styles NOT using bootstrap.</h2>
        <h3 class="text-muted">It's a bit more work, but it gets the job done</h3>
        <p>Notice how the user's markup has the same classes as bootstrap, but they're not inheriting from it.</p>
        <a href="#" class="btn btn-primary">Button.</a>
        <!-- End Html Template -->
    </div>

</div>

:) Happy coding 
  

Wednesday, October 28, 2015

Reset user password from APEX in case of user lockout

With winter 16 we have issue with password lockout when we have two factor enabled

Click here to see the issue

We are experiencing so many lockouts so I came up with this 

global class scheduledPasswordReset implements Schedulable {

 global void execute(SchedulableContext SC) {
Set<String> Ids = new Set<String>();
Set<String> LockIds = new Set<String>();
for (LoginHistory l : [SELECT UserId,LoginTime, status FROM LoginHistory WHERE LoginTime = TODAY ORDER BY LoginTime DESC  ]){
if(!Ids.contains(l.userId)){
Ids.add(l.userId);
if(l.status == 'Password Lockout'){
LockIds.add(l.userId);
}
}
}
system.debug('### '+LockIds);
for(String uId : LockIds){
 System.resetPassword(uId, true);
}

   }

}

Friday, September 11, 2015

@chatter Mention user

Hello everyone after the version 31 below methods are no longer available 

ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null, ConnectApi.FeedType.News, userId);


So how we can do @mention now . see sample code below how to do that .


// Method that takes the list sobject as  parameter and post 


    public static void postOnChatter(List<Sobject> Items){

        List<ConnectApi.BatchInput> batchInputs = new                      List<ConnectApi.BatchInput>();
Integer MAXSIZE = 10 ;// Select Your size
        for (Sobject item : Items) {
            //  initialize the FeedItemInput
            ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
            input.subjectId = item.Id;
            
            // initialize the body of the chatter post
            ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();
            body.messageSegments = new List<ConnectApi.MessageSegmentInput>();
            
            // add the mention to the post
            ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();
            mentionSegment.id = item.OwnerId;
            body.messageSegments.add(mentionSegment);
            
            // add the text containing the Product Name and the tracking information
            ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
            textSegment.text = 'Sample Text';
            body.messageSegments.add(textSegment);
            
            input.body = body;
            ConnectApi.BatchInput batchInput = new ConnectApi.BatchInput(input);
            
            // add the FeedItemInput instances to a list
            batchInputs.add(batchInput);
            
            // postFeedElementBatch() method can process maximum of 500 feeds at a time
            // if the feeds are 500, post them and re-instantiate the list
            if(batchInputs.size() == MAXSIZE){
                ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchInputs);
                batchInputs = new List<ConnectApi.BatchInput>();
            }
        }
        // post the feeds  in the list
        if(batchInputs.size() > 0)
            ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchInputs);
    }

Tips on passing Salesforce AI Associate Certification

  🌟 Motivation to Pursue the Salesforce AI Associate Certification 🌟 The world of technology is in a state of perpetual evolution, and on...