May 9, 2014

Dropbox Authentication In Salesforce - Easy Setup (Authentication Part 1)

From log time managing data is a big deal, and a lot are concerned with it. Multiple options are available to handle this, out of them Dropbox, Box.com, Amazon are the main ones.

In this blog Authentication with Dropbox is explained so developers can get started.

Step 1 : Create an account on Dropbox, then go to this link and create an app. It will create "App Key" and "App Secret" which we will be using in Salesforce. Leave the OAuth2 section blank for now.


Step 2 : Go to salesforce and create this apex class (DropboxController) :

public class DropboxController
{
    //Fetched from URL
    String code ;
    
    public DropboxController()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
    }
    
    public PageReference DropAuth()
    {
        //Authenticating
        PageReference pg = new PageReference('https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=vaabb5qz4jv28t5&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage&state=Mytesting') ;
        return pg ;
    }
    
    public void AccessToken()
    {
        //Getting access token from dropbox
        String tokenuri = 'https://api.dropbox.com/1/oauth2/token?grant_type=authorization_code&code='+code+'&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage'; 
        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenuri);
        req.setMethod('POST');
        req.setTimeout(60*1000);
          
        Blob headerValue = Blob.valueOf('vaabb5qz4jv28t5' + ':' + 'dpmmll522bep6pt');
        String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
        
        System.debug(' You can parse the response to get the access token ::: ' + resp);
   }
}


Step 3 : Now create visualforce page (DropboxPage) :



    
        
    




Step 4 : Replace the code with your values

1 . As you can see we have this in code :

PageReference pg = new PageReference('https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=vaabb5qz4jv28t5&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage&state=Mytesting') ;


You have to replace "client_id" with your "App Key" (redirect_uri is the complete page URL which we've just created). Now as visualforce page is created you can fill the OAuth2 section as shown in the screenshot above in dropbox.

2. Replace "dpmmll522bep6pt" in this line
Blob headerValue = Blob.valueOf('vaabb5qz4jv28t5' + ':' + 'dpmmll522bep6pt');
with you "App Secret"

Step 5 : Don't forget to set the remote site settings for dropbox



Now all set to go. Open the page "https:// ..... /apex/DropboxPage" and hit "Dropbox Authentication". In the debug you will get the access token which you can further use to hit Dropbox APIs.

Please note, code is not beautified as this is just to explain how you can authenticate dropbox with salesforce. A lot more creativity can be applied here.

From here everything is set and you are ready to hit the dropbox API and fetch the data or store the data. Complete documentation is here.

Happy Coding!!

May 7, 2014

Salesforce1 Developer Week - Jaipur Meetup

Salesforce organized a global event where around 70 Salesforce Developer Groups across the world talked about Salesforce1. We are proud to be part of the 1.5 Million developers in the Salesforce Developer Community and celebrated by taking part in Salesforce1 Developer Week on April 27th.

Special attraction of the event was Raja Rao DV (Developer Advocate, Salesforce.com) presented live in the group that what can be built using Salesforce1. Hope now every attendee learned what is Salesforce1 and how to get started.


Followed by Sandeep Singhal (Leader of Jaipur Salesforce Platform Student User Group) explained a little more introduction of Salesforce1 within Salesforce.


Now all were hungry, so it was time for lunch.


All set to go, here comes Amit Jain (Salesforce and Mobile Developer). Amit, presented on how we can develop an app by only points and clicks. It was making everything permanent in mind, what we've learned in last two sessions.


It was time to learn something advance, and who else is best to take this off. Gaurav Kheterpal (Mobile Guru, Salesforce Expert, Speaker, Author (space is not enough)) takes the show away by explaining mobilizing your apps with Salesforce1.




Workbooks were distributed to all, to get started. If you were not one of the attendee then here is the link to download it.


In the end the most awaited part of the event "The Quiz". Where super cool T-Shirts were distributed to all winners.



Over all it was a great success and response from all was very good. If you want to join us in upcoming meetups please join us here.



For more pictures and details of the event visit here.

Jun 12, 2013

Cow and Bull In Salesforce - Let's Brainstorm

Hope may of you are aware of the game Cow & Bull, but those who are not here are the rules

1) Computer will generate a 4 digit number which you need to guess in less than 10 chances
2) This number will not start from 0
3) All digits of the number will be unique (no digit will repeat)

For example:

1234 - is correct
0234 - is wrong
3445 - is wrong

Now user will input a 4 digit number which doesn't starts with 0 and all digits are unique. Computer will then compare with it's generated number and tell you the count of cows and bulls.

What is Cow and Bull

1) Cow: When digits of your number matches digits of computer's generated number on same index

For example: Computer generated > 4580

Your guess > 4619
Count of cows will be one as only one digit matches on same index.

If your guess is > 4689
Then count of cows will be 2 as "4" and "8" both matches at same index

2) Bull: When digit of your number matches digits of computer's generated number but not on same index

For example: Computer generated > 4580

Your guess > 6419
Count of bulls will be one as only one digit ("4") matches (but on same index).

If your guess is > 4689
Then count of bulls will be 2 as "4" and "8" both matches (but on same index)

So if you guessed 4851, then there is ONE cow ("4") and TWO bulls ("8" and "5")



Now it's time to use the brain, here is the site link: http://bmprojects-developer-edition.ap1.force.com/CB_CowAndBull


VFP:


<apex:page controller="CB_CowAndBullController" showHeader="false" sidebar="false">
    <apex:form id="FRM">
        <apex:pageBlock id="PB" title="Cow And Bull">
            
            <apex:pageMessage severity="INFO" escape="false">
                1) Enter 4 digit number which have all digits unique and is not starting from 0 <br/><br/>
                2) Cows: Digits from your number matches computer's number at same index <br/>
                e.g: You Enter -> 1234 and Computer Number -> 1960 <br/>
                1 matches on same index so it will be counted as cow <br/><br/>
                3) Bulls: Digits from your number matches computer's number but not on same index <br/>
                e.g: You Enter -> 1234 and Computer Number -> 9120 <br/>
                1 and 2 matches but not on same index so it will be counted as bull
            </apex:pageMessage>
            <apex:pageMessages id="PM"/>
            
            <apex:pageBlockButtons rendered="{!IF(showButton , true , false)}">
                <apex:commandButton value="Check C&B" action="{!CheckCandB}"/>
            </apex:pageBlockButtons>
            
            <!-- <apex:outputText value="Computer Generated Number : {!CompNumber}"/> -->
            
            <apex:pageBlockSection id="PBS1">
                <apex:pageBlockSectionItem id="PBSI1">
                    <apex:outputLabel value="Please Enter Your Number:"/>
                    <apex:inputText size="4" value="{!userEnteredNUmber}"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            
            <apex:pageBlockTable rendered="{!IF(toDisplayWrapperLst.size > 0 , true, false)}" value="{!toDisplayWrapperLst}" var="wrap">
                <apex:column headerValue="Your Input" value="{!wrap.userInput}"/>
                <apex:column headerValue="Cows" value="{!wrap.cow}"/>
                <apex:column headerValue="Bulls" value="{!wrap.bull}"/>
            </apex:pageBlockTable>
        
        </apex:pageBlock>
    </apex:form>
</apex:page>


Apex Code:


public class CB_CowAndBullController
{
    public Integer CompNumber {get; set;}
    public Integer userEnteredNUmber {get; set;}
    //To maintain the user inputs
    public List<userInputResults> toDisplayWrapperLst {get; set;}
    //Flag to show the button which compare the user input with computer's generated number
    public boolean showButton {get; set;}
    
    public CB_CowAndBullController()
    {
        //Number entered by user
        userEnteredNUmber = 0 ;
        
        showButton = true ;
        
        toDisplayWrapperLst = new List<userInputResults>() ;
        
        //Generating 4 digit number which doesn't start with 0 and no number is repeated
        boolean flag = false ;
        while(!flag)
        {
            Integer tempVar = Integer.valueOf(Math.Random() * 10000) ;
            if(checkNumber(tempVar))
            {
                flag = true ;
                CompNumber = tempVar ;
            }
        }
    }
    
    private Boolean checkNumber(Integer num)
    {
        //Pattern for 4 digit number which doesn't start with 0 and no number is repeated
        Pattern nonZeroPattern = Pattern.compile('([1-9])(?!.*\\1)([0-9])(?!.*\\2)([0-9])(?!.*\\3)([0-9])(?!.*\\4)');
        Matcher nonZeroMatcher = nonZeroPattern.matcher(''+num);
        if(nonZeroMatcher.matches())
             return true;
        else
            return false ;
    }
    
    public PageReference CheckCandB()
    {
        if(checknumber(userEnteredNUmber))
        {
            //Logic to compare user input and computer's generated number
            Integer cow = 0 ;
            Integer bull = 0 ;
            String UEN = string.valueOf(userEnteredNUmber) ;
            String CGN = string.valueOf(CompNumber) ;
            
            for(Integer i = 0 ; i < UEN.length() ; i++)
            {   
                for(Integer j = 0 ; j < CGN.length() ; j++)
                {
                    if(UEN.subString(i , i+1) == CGN.subString(j , j+1))
                    {
                        if(i == j)
                            cow = cow + 1 ;
                        else
                            bull = bull + 1 ;
                    }
                }
            }
            toDisplayWrapperLst.add(new userInputResults(cow, bull, userEnteredNUmber)) ;

            if(cow == 4)
            {
                showButton = false ;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Congratulations! You guessed it right in ' + toDisplayWrapperLst.size() + ' chances.'));
            }
            else
            {
                if(toDisplayWrapperLst.size() > 9)
                {
                    showButton = false ;
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'You failed to guess the number in 10 chances. Better luck next time.'));
                }
            }
        }
        else
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter a 4 digit number which does not start with 0 and no number is repeated' ));
        }
        return null ;
    }
    
    //Wrapper to maintain number of cows, bulls and user input
    public class userInputResults
    {
        public Integer cow {get; set;}
        public Integer bull {get; set;}
        public Integer userInput {get; set;}
        
        public userInputResults(Integer c, Integer b, Integer ui)
        {
            cow = c ;
            bull = b;
            userInput = ui ;
        }
    }
}


Would love to hear the feedback.

Apr 30, 2013

How Can I Become A MVP (Force.com)

Recently my MVP title is renewed (Extra! Announcing our newest and renewed Force.com MVPs) and this question bothered many from time to time "How can I become a MVP"? 

Don't focus on how to become a MVP, focus only on the motive behind the program. It is stated that "Force.com MVP program recognizes outstanding contributors and technological leaders in the Force.com cloud platform ecosystems. Force.com MVPs are being called out for willingly sharing their expertise with others, demonstrating stewardship of the community in which they play an integral part, advancing the community body of knowledge and strengthening the developer network." 

Now there are multiple ways to do this, let's talk about some of them: 

1) Contribution via discussion boards, which is the heart of community. We've multiple discussion boards where you can share your knowledge with other community members.


2) Evangelism of the technology through independent publication such as blogs/whitepapers/FB Page 

3) Contribution to open sources. If you've ever thought about sharing some code samples or some big projects so don't let it be restricted to only your personal blogs. Make them live here:


4) Get Social and stay connected with other peers on social sites like

  • Twitter : Follow official accounts @forcedotcom @salesforce and use #askforce if you need any help or you want to help the community
  • Facebook : Like the official page and stay connected with the latest news and events
  • LinkedIn etc.

5) Participate as much as you can via attending live webinars (you can get the information from social sites or here), online events (where you get chance to win some cool stuff), online challenges like this 

6) Participate in local developer user group meetings. You can get the list of all developer user groups here.

7) Participate in big events like Dreamforce, Cloudstock etc.

List never ends and it's benefits too, like by doing all this

  • Your knowledge will be increased.
  • Your networking will be strong
  • Will be acknowledged globally
  • Significant increase in offers from companies
  • Domain will not be restricted any more
  • After actively participating in events your wardrobe will be full of some cool stuff like Jackets, T-Shirts, Caps, Bags, Trophies, Books, Hoodies


Above benefits are for sure, and if you are entitled as MVP then there are some additional benefits to above:

  • You'll get sponsored trips to SF for events like MVP Summit
  • You'll get free passes to Dreamforce
  • Highlighted community profile, (here is mine)
  • Early access to feature previews and releases, with direct feedback to the PMs on these products
  • Access to chatter groups where all MVPs jam together



I don't know where to stop...so now you have the links and I hope you know what to do. GOOD LUCK!

Make our community rock!!


Mar 16, 2013

Jaipur DUG Cloud Trivia Winners

Yes! It's true, winners list of Jaipur DUG Cloud Trivia is out.
Thank you all who participated. After getting such an awesome response, I hope I'll be able to arrange some more contest like this. It is just to motivate you guys to stay updated with the latest release, and I must say you guys did a great job.

Here is the winners list :-



Amit Jain
Deepali Jain
Pankaj Kabra
Er Deepak Sheoran
Kumawat Deshraj
Jinesh Goyal
Ranu Jain
Mohit Chawla
Ashish Agarwal






Please drop me an email on "ankit.salesforce@gmail.com" so we can co-ordinate how you can collect your prize (T-Shirt/Workbook/CheatSheets/Salesforce Touch Platform Book).

Stay connected with us to know info about more contest like this :-
3) Meetup

Dec 27, 2012

Streaming APIs - Easy Code


Streaming API is useful when you want notifications to be pushed from the server to the client based on criteria that you define.

The sequence of events when using Streaming API is as follows: (explained in detail later)
1. Create a PushTopic based on a SOQL query. This defines the channel.
2. Clients subscribe to the channel.
3. A record is created or updated (an event occurs). The changes to that record are evaluated.
4. If the record changes match the criteria of the PushTopic query, a notification is generated by the server and received by the subscribed clients.

Before we get started, I recommend you to go through these topics:

1) Push Technology
2) Bayeux Protocol, CometD, and Long Polling


We will achieve this once we are done with all steps (given below):





Now follow these steps:

Prerequisites:
1) The “Streaming API” permission must be enabled -> "Your Name > Setup > Customize > User Interface"
2) The logged-in user must have “Read” permission on the PushTopic standard object to receive notifications.
3) The logged-in user must have “Create” permission on the PushTopic standard object to create and manage PushTopic records.
4) The logged-in user must have “Author Apex” permissions to create a PushTopic by using the Developer Console.


Step 1: Create an Object - In our case we will use Account

Step 2: Create a PushTopic
Use the Developer Console to create the PushTopic record. You can use either Developer Console or Workbench. If needed these records can be updated.

"Your Name > Developer Console"


PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'RefreshAccounts';
pushTopic.Query = 'SELECT Id, Name FROM Account';
pushTopic.ApiVersion = 26.0;
pushTopic.NotifyForOperations = 'All';
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;


Step 3: Create Static resource

1. Download the CometD compressed archive (.tgz) file from http://download.cometd.org/cometd-2.2.0-distribution.tar.gz
2. Extract the following JavaScript files from cometd-2.2.0-distribution.tar.gz:
• cometd-2.2.0/cometd-javascript/common/target/org/cometd.js
• cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/jquery-1.5.1.js
• cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/json2.js
• cometd-2.2.0/cometd-javascript/jquery/src/main/webapp/jquery/jquery.cometd.js


File Name
Static Resource Name
cometd.js
Cometd
jquery-1.5.1.js
Jquery
json2.js
json2
jquery.cometd.js
jquery_cometd




Step 4: Test the PushTopic Channel

Here is the code sample

Visualforce Page


<apex:page id="PG" controller="StreamingAPIController">
<apex:form id="FRM">

    <apex:includeScript value="{!$Resource.cometd}"/>
    <apex:includeScript value="{!$Resource.jquery}"/>
    <apex:includeScript value="{!$Resource.json2}"/>
    <apex:includeScript value="{!$Resource.jquery_cometd}"/>

    <apex:actionFunction name="GetRefreshedAccounts" reRender="PB,PBT"/>

    <script type="text/javascript">
        (function($)
        {
            $(document).ready(function() {
                
                // Connect to the CometD endpoint
                $.cometd.init({
                    url: window.location.protocol+'//'+window.location.hostname+'/cometd/24.0/',
                    requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
                });
                
                // Subscribe to a topic. JSON-encoded update will be returned in the callback
                // In this example we are using this only to track the generated event
                $.cometd.subscribe('/topic/RefreshAccounts', function(message)
                {
                    //You can use message as it will return you many attributes
                    //I am just using to track that event is generated
                    GetRefreshedAccounts();
                });

            });
        })(jQuery)
    </script>

    <apex:pageBlock id="PB">
        <apex:variable var="count" value="{!0}" />
        <apex:pageBlockTable id="PBT" value="{!getRefreshedAccount}" var="AllAcc">
            
            <apex:column headerValue="S.No.">
                <apex:variable var="count" value="{!count+1}" />
                {!count}
            </apex:column>
            <apex:column value="{!AllAcc.Name}" headerValue="Name"/>
            
        </apex:pageBlockTable>
    </apex:pageBlock>

</apex:form>
</apex:page>

Apex Class


public class StreamingAPIController
{
    //Everytime page is reRendered it will get refreshed values of account
    public List<Account> getRefreshedAccount
    {
        get
        {
            return [select Id, Name from Account LIMIT 50000] ;
        }
        set;
    }
    
    public StreamingAPIController()
    {
    }
}


This is very small and simple sample code, you can do a lot more with streaming APIs. Please refer these documents to learn more:

1) http://www.salesforce.com/us/developer/docs/api_streaming/api_streaming.pdf
2) http://www.salesforce.com/us/developer/docs/api_streaming/index.htm
3)http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_Streaming_API

Dec 22, 2012

Uploading Multiple Attachments into Salesforce - Simple Code

Okay, so here is the simple code to upload multiple attachments into Salesforce. Please note that I've used standard controller ("Account" in the code) so you need to pass the record Id in parameter. You can also change this according to your need as code is dynamic.

So first option allow you to select how many files you want to upload. Say, you have selected "5", then it will give you 5 options to select files and once you click on "Upload" it will upload the files as attachments to the associated record.



Visualforce Page Code:


<apex:page standardController="Account" extensions="MultipleUploadController">
    <apex:form>
        <apex:pageBlock title="Upload Multiple Attachment to Object">
            
            <apex:pageBlockButtons>
                <apex:commandButton value="Upload"  action="{!SaveAttachments}"/>
            </apex:pageBlockButtons>
            
            <apex:pageMessages id="MSG"/>
            <apex:actionFunction name="ChangeCount" action="{!ChangeCount}"/>
            
            <apex:pageblocksection>
                            
                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="How many files you want to upload?"/>
                    <apex:selectList onchange="ChangeCount() ;" multiselect="false" size="1" value="{!FileCount}">
                        <apex:selectOption itemLabel="--None--" itemValue=""/>
                        <apex:selectOptions value="{!filesCountList}"/>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
            
            </apex:pageblocksection>
            
            <apex:pageBlockSection title="Select Files" rendered="{!IF(FileCount != null && FileCount != '', true , false)}">
                <apex:repeat value="{!allFileList}" var="AFL">
                    <apex:inputfile value="{!AFL.body}" filename="{!AFL.Name}" />
                    <br/>
                </apex:repeat>
            </apex:pageBlockSection>
            
        </apex:pageBlock>
    </apex:form>
</apex:page>


Apex Code:


public class MultipleUploadController
{   
    //Picklist of tnteger values to hold file count
    public List<SelectOption> filesCountList {get; set;}
    //Selected count
    public String FileCount {get; set;}
    
    public List<Attachment> allFileList {get; set;}
    
    public MultipleUploadController(ApexPages.StandardController controller)
    {
        //Initialize  
        filesCountList = new List<SelectOption>() ;
        FileCount = '' ;
        allFileList = new List<Attachment>() ;
        
        //Adding values count list - you can change this according to your need
        for(Integer i = 1 ; i < 11 ; i++)
            filesCountList.add(new SelectOption(''+i , ''+i)) ;
    }
    
    public Pagereference SaveAttachments()
    {
        String accId = System.currentPagereference().getParameters().get('id');
        if(accId == null || accId == '')
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'No record is associated. Please pass record Id in parameter.'));
        if(FileCount == null || FileCount == '')
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select how many files you want to upload.'));

        List<Attachment> listToInsert = new List<Attachment>() ;
        
        //Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
        for(Attachment a: allFileList)
        {
            if(a.name != '' && a.name != '' && a.body != null)
                listToInsert.add(new Attachment(parentId = accId, name = a.name, body = a.body)) ;
        }
        
        //Inserting attachments
        if(listToInsert.size() > 0)
        {
            insert listToInsert ;
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.INFO, listToInsert.size() + ' file(s) are uploaded successfully'));
            FileCount = '' ;
        }
        else
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select at-least one file'));
            
        return null;
    }
    
    public PageReference ChangeCount()
    {
        allFileList.clear() ;
        //Adding multiple attachments instance
        for(Integer i = 1 ; i <= Integer.valueOf(FileCount) ; i++)
            allFileList.add(new Attachment()) ;
        return null ;
    }
}


You can enhance the code if you like, as I've provided the basic code which is re-usable. Also you can change the object passed in standard controller and code will handle the rest. URL should have ID else you will get error on UI :-)

Say, I've saved my VFP code as "MultipleUpload", so my URL will be https://...../apex/MultipleUpload?id=XXXXXXXXXXXXXXX (account id in this code).

Happy Coding.