Thursday, 14 April 2011

Displaying Barcharts and piecharts of active Opportunities for every Account on vfpage

In Salesforce we can create barcharts,piecharts by creating reports on an object and we cannot display them on vfpage . when i was exploring on flex barcharts and piechart i got an idea to show Barcharts and Piecharts for active Opportunities of an account on Vfpage, so i have implemented this.

Barcharts And Piecharts in Flex:- 

  In Flex we have tags <mx:BarChart>,<mx:PieChart> to design barcharts and piecharts.

  We can bind data to them using  "dataprovider=""" attribute of  above tags.

 Example:-  
  
Piechart:- 
              <mx:PieChart width="300"
                      height="250"
                      dataProvider="{opps}"      //opps is a array collection .Here we are binding data to piecharts.
                      visible="{opps.length > 0}" // visible when we have data.
                      includeInLayout="{opps.length > 0} >
             <mx:series>
                 <mx:PieSeries field="Amount" startAngle="90"/>
             </mx:series>
             </mx:PieChart>
 

 Barcharts:- 


         <mx:BarChart id="chart" dataProvider="{opps}" width="300" height="250">
            <mx:verticalAxis>
              <mx:CategoryAxis dataProvider="{opps}" categoryField="Name"/>  // binding field to vertical axis.
            </mx:verticalAxis>
            <mx:series>
               <mx:BarSeries xField="Amount"/> // binding Amount field to x -axis.
            </mx:series>
            </mx:BarChart> 





Implementation:-

Here  there are two ways to implement this.

                     1. Every time we need to provide force.com credentials statically.
               
                    2. Passing server id,user details and account  id using Flashvar  property in <apex:Flash> tag .

i have done this using  <apex:flash>

Step 1:- In this step we need design a flex app that shows barcharts and piecharts and active opportunities list

          a .  Open flex builder, create a project and  name it as "Barcharts Demo" and select application type as Desktop application and finally click on finish.

                   Goto-->file-->New-->Flexproject.

          b.   In Force.com toolkit for flex, in bin folder we can find two files

                               1.Flex-Air swf file

                               2. Force-Flex swf file
             
                copy the both files ,and paste them in to your flex project libs folder.

          c.  Right click on your project-->New-->MXML component.Name it as BarchartsDemoapp.

                   Right click on that BarchartsDemoapp.Mxml file  and  select "Set as Default Application".

                   Now open BarchartsDemoapp.Mxml.
 
          d.  Copy the following code and paste it in that file

BarchartsDemoapp.Mxml file

   <?xml version="1.0" encoding="utf-8"?>
     <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"                                                                                             xmlns:salesforce="http://www.salesforce.com/"
                                 layout="absolute" width="100%" height="100%" 

                                 backgroundGradientAlphas="[1.0, 1.0]"
                                 backgroundGradientColors="[#FFFFFF, #FFFFFF]" 

                                 applicationComplete="init()">
   
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import com.salesforce.results.QueryResult;
            import com.salesforce.results.LoginResult;
            import com.salesforce.AsyncResponder;
            import com.salesforce.objects.LoginRequest;
           
            [Bindable]
            private var opps:ArrayCollection;
           
            private function init():void
            {
                var lr:LoginRequest = new LoginRequest();
                lr.session_id = parameters.sid;   // here we have pass this from apexpage using flashvars
                lr.server_url = parameters.surl;  //
here we have pass this from apexpage using flashvars
                lr.callback = new AsyncResponder(loginHandler);
                force.login(lr);
            }       
           
            private function loginHandler(result:LoginResult):void
            {
                force.query("SELECT Name, Amount FROM Opportunity WHERE Account.Id = '" +
                    parameters.aid(
here we have pass this from apexpage using flashvars) + "'", new                   AsyncResponder(queryHandler));
            }
           
            private function queryHandler(result:QueryResult):void
            {
                opps = result.records;
            }
        ]]>
    </mx:Script>
 <salesforce:Connection id="force"/>
<mx:HDividedBox  height="50%" width="100%">
    <mx:Panel id="panel1" title="Piechart View" height="100%" width="33%">
        <mx:PieChart width="300"
                      height="250"
                      dataProvider="{opps}"
                      visible="{opps.length > 0}"
                      includeInLayout="{opps.length > 0}"
                      showDataTips="true"
                  >
             <mx:series>
                 <mx:PieSeries field="Amount" startAngle="90"/>
             </mx:series>
         </mx:PieChart>
         </mx:Panel>
         <mx:Panel id="panel" title="Barchart View" height="100%" width="33%">
                   <mx:BarChart id="chart" dataProvider="{opps}" width="300" height="250">
                        <mx:verticalAxis>
                            <mx:CategoryAxis dataProvider="{opps}" categoryField="Name"/>
                       </mx:verticalAxis>
                       <mx:series>
                       <mx:BarSeries xField="Amount"/>
                       </mx:series>
                  </mx:BarChart>
      </mx:Panel>
      <mx:Panel id="panel2" title="OpportunityList" height="100%" width="40%">
             <mx:DataGrid id="dg" height="100%" width="100%" dataProvider="{opps}">
       
            </mx:DataGrid>
       
     </mx:Panel>
</mx:HDividedBox>      
</mx:Application>

 Execute the project using CRTL+F11  or right click on project select "Runas"-->Desktop application.



Now you can find  "BarchartsDemoapp.Swf" file in the bin-debug  floder of  your project.Copy that swf file save it to your computer.


Step 2:- Uploading swf file into Force.com StaticResources.

          a.  Login to your Force.com  account.

          b.  Goto-->Setup-->AppSetup-->Develop-->Static Resources-->Click on NEW.

               Give Name as "BarchartsDemoapp" -->Browse the BarchartsDemoapp.swf file-->Select cache control as"public" and  Save the file.
 
Step 3:- We have the <apex:flash > tag to embeded the Swf file on Vfpage.

   Example:- 
                 <apex:flash src="{!$Resource.BarchartsDemoapp}" width="100%" height="700"   flashvars="sid={!$Api.Session_ID}&surl={!$Api.Partner_Server_URL_150}&aid={!accountId}"/>
 

      Explanation:-  from here we are passing  Session_Id,Server_Url,accountId  to flex .
 



Step 4:-  Create Apex page to display Accounts on vfpage and to display barcharts ,piecharts and active Opportunities list on vfpage.


                Goto-->Setup-->AppSetup-->Develop-->pages-->Click on New-->Name it as "Account Opportunities".

  Copy the following code and paste it  in that page.

<apex:page standardController="Account" recordSetVar="acc" extensions="AccountDetailController">
<script>
 function getId(id)
 {

    window.top.location.href='/apex/accountpage?id='+id;       
 }
</Script>
<apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!acc}" var="acc1">
                    <apex:column headerValue="Accounts">
                            <apex:CommandLink onClick="getId('{!acc1.id}')">
                               {!acc1.Name}
                            </apex:Commandlink>
                    </apex:column>
            </apex:pageBlockTable>
       </apex:pageBlock>
     
       <apex:pageBlock title="Active Opportunities for Account">
                   
            <apex:flash src="{!$Resource.piebarcharts}" width="100%" height="700"       flashvars="sid={!$Api.Session_ID}&surl={!$Api.Partner_Server_URL_150}&aid={!userId}"/>
      </apex:pageBlock>
   </apex:form>
</apex:page>
 
AccountDetailController:-

  Goto-->Setup-->AppSetup-->Develop-->ApexClasses-->Click on New

        public class AccountDetailController
       {
         public AccountDetailController(ApexPages.StandardSetController controller) {
        }
        public String userId;
        public String getuserId() {return ApexPages.currentPage().getParameters().get('Id');}
       }

Save the Controller.


Now execute the page,

             /apex/Account Opportunities
              
Initially you can see only accounts on your page and with empty charts.

Now click on any account then,you can see barchats, piecharts build dynamically with opportunities data for that account.

Now you can see.........

             
          
 
  



















Now you can click on every account,then see the output.
         

Flex SMS- Application using Http-Services.


I have created a small application in flex that sends SMS from flex to mobile. i have created this application by using Flex-Webservices,so first i will explain  briefly about webservices.

Flex Remoting services:-

           Flex remoting services are used to make following

                       1. Http calls to webservices
                       2. Webservices->Call Soap+Wsdl based web-services.
                       3. Remoting ->Call remote object services such as Coldfusion (or) Java.

HTTP - service is used to make Http request  and handle results.When you call Http service object's "send()" method,it makes a http request to specified "url" and Http response is returned(asyncronously). Every Http call returns a token call as "Asynctoken".The Http call results either result (or) fault,this can be handle by using "Responder". In flex we can Http-services either from MXML or from Action script.


Calling Http -services  in Flex MXML Component:-

In Flex we have " <mx:HTTPService>" tag to use Http-services.

Example:-          <mx:HTTPServices  id ="httpservice"

                             url="Your webservice url... to make request"

                             method="Get"

                             requestformat = "Text"

                            result ="resultHandler(event)"

                            fault = "faultHandler(event)"    / >




Calling Http- services in Action Script:-

 To call Http-services we need to import following

                import mx.rpc.http.HTTPService;
           
                import mx.rpc.events.ResultEvent;
            
                import mx.rpc.events.FaultEvent;

sample code:-

                var http: HTTPService = new HTTPService();

                http.url=" you webservice url.........";

                http.resultFormat = "text";
      
                http.method = "POST";
               
                http.addEventListener("result", httpResult);
               
                http.addEventListener("fault", httpFault);
                
               http.send();

  For sending Sms from flex to mobile we need to have SMS gateways that provides Api services  to make requests, my colleague charan explored on that he find many Sms-gateways providing Api servies to send sms. i haves  used following  gate ways,

                                            Sms Global   and Clickatell.


Now Creating Application:-


 Step 1:-  Creating Project in Flex3

                   Goto File-->New-->Flex Project

                   Name it as "SMS Demo App"  and Select Application type as "Web Application" and click on finish.

 Step 2:-  Goto  your project in project navigation window--> Click on src folder--> Double click on ProjectName.MXML component. Then in developing window Mxml component is opened.Now copy the following code and paste in Mxml component.


project name.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 <mx:Script>
 <![CDATA[
   import mx.rpc.http.HTTPService;

   import mx.controls.Text;
 
   import mx.controls.Alert;

   import mx.rpc.http.HTTPService;
        
   import mx.rpc.events.ResultEvent;
          
   import mx.rpc.events.FaultEvent;

   private var Fname:String;
 
   private var Phone:Number;
 
   private var msg:String;
 
   private var sUsername:String = "******";// user name of sms global or clickatell.
 
   private var sPassword:int=*******;// password of smsglobal or clickate.
 
   private var sId:String="Flex testing Sms";
 
 function send():void
 {
 
       Phone = Number(con.text);
    
       msg = inputmsg.text;
          
      Alert.show("phone number: "+Phone+"\nmessage: "+msg);
    
      var http: HTTPService = new HTTPService();
    
      http.url =" http://api.clickatell.com/http/sendmsg?user=hari****&password=*****&api_id=****&to="+Phone+"&text="+msg;  // URL to send Http requests....
    
    
     // http.url  = "http://www.smsglobal.com/http-api.php?action=sendsms&user="+sUsername+'&password='+sPassword+'&from='+sId+'&to='+Phone+'&text='+msg;  //  SMS  Global  Url to send Http requests....
 
      http.resultFormat = "text";
    
      http.method = "POST";
            
      http.addEventListener("result", httpResult);
            
      http.addEventListener("fault", httpFault);
              
      http.send();
    
     }
     public function httpResult(event:ResultEvent):void {
                var result:Object = event.result;
            //Do something with the result.
            }

    public function httpFault(event:FaultEvent):void {
                var faultstring:String = event.fault.faultString;
                Alert.show(faultstring);
              
    }

  ]]>
 </mx:Script>

 <mx:Form id="smsform" label="Sample Sms App">
            <mx:FormItem label="To(Phone Number)" required="true">
                <mx:TextInput id="con"  maxChars="12"/>
            </mx:FormItem>
            <mx:FormItem  label="MessageBody" required="true">
                <mx:TextArea id="inputmsg" />
            </mx:FormItem>
            
      <mx:Button label="Send" id="myButton" click="send()" />

 </mx:Form>

</mx:Application>

        Now you get form...

    
Note:- first you need to create Accounts @ Sms gate ways to use services.After you have created account you can get username and password.

Tuesday, 12 April 2011

Integrating Force.com and Flex using Force.com Tool kit for Flex.

Developing Basic Application:-

 For developing Flex and Force.com apps we need to install FlexBuilder3 and we need Force.com toolkit for Flex.


You can download Force.com tool kit for Flex from here.


Importing the Library In to your Project:-


You can find the libraries in the bin folder of the toolkit ZIP file. You'll need force-flex.swc if you're building a browser-based Flex application or force-air.swc if you're building a desktop AIR application. To import the toolkit library into your project, you'll need to place it in your project's libs folder

The Connection Object


The main class within the toolkit is the Connection class. This class gives you access to all the key Force.com operations such as login, query and update. You'll need to create an instance of this class and keep that instance alive for the duration of your communication with Force.com. The easiest way to create an instance of the class is to declare it in MXML like this:


                   <Salesforce :Connection  id ="Force">



The salesforce namespace should automatically get filled in for you by the IDE but if it doesn't you can add the following attribute to your application MXML's root element:


                    xmlns:salesforce="http://www.salesforce.com"


Alternatively you can create an instance of the class directly through ActionScript - the fully-qualified name is com.salesforce.Connection.


Process:-
   
 Step1:-  Open Flexbuilder3  and create project.

              Flexbuilder3-->File-->New-->FlexProject.

              Name it as "Flex Force Demo" ,select Application type as "Desktop Application" and application 

              server type as "None" finally click on Finish

Step2:- In Force.com toolkit for flex, in bin folder we can find two files

                               1.Flex-Air swf file

                               2. Force-Flex swf file
             
            copy both files ,and paste them in to your flex project libs folder.

Step3:- Goto your project in project navigation window, And double click on .MXML file.

            Projectname-->src-->Projectname.MXML file or Main.MXML
             
             Now copy and paste the following code to get salesforce records in to grid in flex.

             


=======================================================================
            <?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication  applicationComplete="init()" xmlns:mx="http://www.adobe.com/2006/mxml"    layout="absolute" xmlns:salesforce="http://www.salesforce.com/">
<salesforce:Connection  id="force" />
<mx:DataGrid id ="dg" left="10" right="119" top="10" bottom="55"><!-- Decalre datagrid to bind result data to datagrid-->
</mx:DataGrid>
<mx:Script>
<![CDATA[
import com.salesforce.results.LoginResult;<!-- To handle the login result(valid or invalid)-->
import com.salesforce.results.QueryResult;<!--To Handle results-->
import com.salesforce.AsyncResponder;<!--To Handle Response from Force.com>
import com.salesforce.objects.LoginRequest;<!--To Handle login Request-->
private function init(): void{
var lr:LoginRequest=new LoginRequest();
lr.username="Force.com user Name";
lr.password="Password and Securitytoken";
lr.callback=new AsyncResponder(loadGrid);
force.login(lr);    
}
private function loadGrid(lr:LoginResult):void{
force.query("Select * From Account", 
   new AsyncResponder( function(qr:QueryResult):void{
    dg.dataProvider = qr.records;<!-- here we are binding result data to data grid using data grid id "dg" and data provider is the property of data grid to bind data to datagrid-->
   })
  
 );
   
}
]]>
</mx:Script>
</mx:WindowedApplication>








==================================================================
in the above example we are querying  data from Account Standard object.

AsyncResponder is used handle the result from Force.com.

To run Project click  Ctrl+F11   or goto project-->rightclick-->Runas-->Desktop Application

Now you can see results in data grid.


Note:- For every flex project SWF files are created in "bin-debug" Folder.

  

Integrating Force.com and Flex

By integrating Force.com and Flex, we can access Salesforce.com objects into flex local data store,where we can create new records,edit and delete records.And we can build Barcharts,Piecharts with  data,which we can get by querying from salesforce object to flex).We can work even in offline also from flex on salesforce objects because we have important feature like      Automatic periodic synchronization of data between the local data store and the Force.com cloud,So what ever changes we  made to local data store are reflected in to Force.com cloud using API calls .Flex frame work for Force.com automatically provides Login Functionality and login Validation.


                 We can Display Barcharts,Piecharts on Visualforce page in Salesforce.com Using SWF files.We can pass variable from salesforce.com to flex by using Flashvar property in <apex:flash> tag.


Integration Ways:-


We can integrate Flex and Force.com in two ways


              1. Using Force.com Tool kit for Flex.


              2. Using Adobe Fash builder Force.com using WSDL .

Force.com Flex framework


The Force.com Flex framework is comprised of a library of Action Script classes to help you more easily retrieve, display, and edit salesforce.com data. For desktop applications, the framework builds on the client-side data management included in Adobe Lifecycle Data Services, but does not include the LCDS server-side data management functionality. The Force.com Flex framework includes:
·         Login functionality, including a UI and error messages.
·         An API for making multiple, asynchronous web service requests to the Force.com cloud to retrieve, save, or delete records.
·         UI components and data classes for displaying, editing, and managing local data changes.
·         The automatic creation and management of a local data store of salesforce.com data for offline support.
·         An API for saving changes to both the local store and the Force.com cloud.
·         Automatic periodic synchronization of data between the local data store and the Force.com cloud.
·         Online and offline data synchronization and management.
·         A conflict resolution service that detects conflicts between the local data store and the Force.com cloud and provides a UI for users to resolve the conflicts.
·         UI components to provide user feedback as status bar messages or toast notifications.
When you create a Force.com Flex project in Flash Builder for Force.com, your project will already include these framework classes in its library folder

Adobe Flash Builder for Force.com



Adobe Flash Builder for Force.com is an IDE developed jointly by Adobe and salesforce.com that gives developers a single, powerful tool for building Force.com Flex applications that can be deployed to the browser or the desktop. For browser applications, you create a SWF file that is referenced on an HTML page (either on the salesforce.com website or any other website) and rendered by Adobe Flash Player. For desktop applications, you create an AIR file that you distribute to your clients. The AIR runtime installs the AIR package on the client computer as a desktop application and renders the content and interacts with the operating system when the client runs the application.

What is Flex?


Flex is a free, open source framework comprised of a library of Actionscript classes (Action Script is the scripting language for the Flash Player) and executables to help you more quickly and easily develop, compile, and interactively debug applications. The Flex framework includes classes for over 100 extensible components, including UI controls (buttons, list boxes, sliders, steppers, data grids, charts, and more), containers (VGroup, HGroup, Panel, Form, and more to help you build adaptive application interfaces), managers (for styles, drag and drop, focus, popups, cursors, browser history and deep links, and more), remote procedure calls (HTTP request, web services, and remote objects), formatters, valuators, and utilities.

What is Salesforce.com?

Salesforce.com is a world leader in providing software as a service (SaaS) in which they host business software and companies purchase subscriptions to use it.The software solution consists of a family of applications and pre-built database tables for you to store, view, and manipulate data. The application you use to access the data is usually a web application, but salesforce.com also provides mobile applications. The data is stored on servers maintained and managed by salesforce.com. This type of service is also referred to as cloud computing; the cloud is the Internet where all the applications and data live. Most prebuilt functionality for salesforce.com offerings is for customer relationship management (CRM) with tailored solutions for sales, service, marketing, small business, and so on. The applications and the database tables are highly customizable and security is role-based.