Sunday 31 July 2011

Overriding Record Type with Vfpage.

Hai Friends this time cam with important topic "Overriding RecordType with Vfpage".This is Very simple and impotant.We can't achieve this Customization, we need to write Script for this.
Step1:-
First Create a Recordtype on an object.
Goto-->Setup-->Appsetup-->Create-->Object--> Create Record Type.
 Suppose like 'Accountrecordtype',
Step2:-
Create Vfpage ,in that Vfpage Code include following code for overriding record type with Vfpage.
===============================
<script language="javascript">

    if('{!account.RecordType.name}' != 'Accountrecordtype'){
        window.location = '/{!account.id}?nooverride=1';
    }
</script>
================================
Now Override the View button with that page.
Now click on the record which is having  Accountrecordtype Record type.

Cheers,
Haribabu Amudalapalli


Monday 25 July 2011

Adding Rows Dynamically to Page block Table

Now i am going to explain a simple example,i.e how we can add rows dynamically to Pageblocktable,how to save records.
Screen:-
   <apex:page controller="multiAccountInsert">
<apex:form >
<apex:sectionHeader title="flexandsalesforceblog" subtitle="AddRows" help="Http://flexandsalesforce.blogspot.com"/>
   <apex:pageBlock title="Add row Dynamically" >
     <apex:pageBlockButtons location="bottom">
         <apex:commandButton value="Save" action="{!save_close}" rerender="error"/>
       </apex:pageBlockButtons>
       <Div align="right">
             <apex:inputText value="{!num}" style="width:45px"/>
             <apex:commandButton value="Add rows" action="{!add_rows}"/> 
       </Div>
       <br/>
      <apex:pageBlockTable value="{!accts}" var="a" id="table">
         <apex:column headerValue="Name">
               <apex:inputField value="{!a.Name}"/>
          </apex:column>
          <apex:column headerValue="phone">
             <apex:inputField value="{!a.phone}"/>
         </apex:column>
         <apex:column headerValue="website">
             <apex:inputField value="{!a.website}"/>
         </apex:column>
       </apex:pageBlockTable>
   </apex:pageBlock>
    </apex:form>
</apex:page>


AddrowController:-



public class addrowCon

  public integer num { get; set; }
  public List<Account> accts {get; set;} 
  public addrowCon()
  {
     accts = new List<Account>(); 
     accts.add(new Account());    
  }
   public PageReference add_rows() {
    for(integer i=0;i<num ;i++)
        {
          accts.add(new Account());    
        }
        
        return null;
     }
  public PageReference save_close()
  {       insert accts;
     PageReference home = new PageReference('/home/home.jsp');
     home.setRedirect(true);
     return home;
  }
}

Tuesday 19 July 2011

Salesforce To Salesforce

Hai Friends, Now i came with the topic "Salesforce to Salesforce",
Introduction :- Salesforce to Salesforce enables you to share records among the business partners.
Step1:-
To establish connection from one organization to another salesforce organization ,we need to enable settings first in both organizations.
Set up--> AppSetup-->Customize-->Salesforce to Salesforce--> Settings.
After enabling settings we need to add another salesforce organization Name and it's Email as Contact in to parent salesforce organization.
Step2:-
Now you can find Tab 'Connections', add that Tab to Tabs bar.
Step3:-  Sending Invitation to another organization.
Now click on 'Connection Tab',click on New--> Select  the contact ,that we have created as per in earlier step--> Click on Save&Send Invite.
Then Email will send to Email,which is associated in that contact.
Step4:-
In that Email,we can get an Link,Click on link and give the login details of client (add contact  sales force organization login details).Now you can see the connection invitation in child salesforce organization.
Click on Accept,Now this allows you to share lead, opportunity, account, contact, task, product, opportunity product, case, case comment, attachment, or custom object records with your business partners. With Salesforce to Salesforce, you can share records with one or more connections, and each connection can accept records you share with them - even if other connections have accepted the same record.
Step 5:- I want to share Accounts
First publish this object from parent connection,for that
Click connection detail page,there you can find the Related list "Publish Object",there you can find button 'publish/unpublish'.Click on that button ,then in new window you can see all the available objects for connection.select Account click on Save.
Now goto business partner Organization,on Connection Detail page you can find related list for Subscribe object, click on button 'subscribe/unsubscribe',click on that button,select object from pick list and click on save. Now to share account records goto parent Salesforce organization ,select Account records from list view of Account records and click on 'Forward to Connections', there you can find list of  Available connections in your organization,select organization and click on save.
Then that Account record will be created in Account object of the business partner.
In this way we can share account records from parent org to business partner organization.
Step 5:- I want to share  contact and opportunities associated with an Account record
We can achieve this by publishing contacts and opportunity objects to business partner and he must subscribe to that objects also.Now send the account record which is associated with above contact and opportunity objects as we discuss in earlier step.

Questions
1. My organization Having 15000 records in Accounts object, can we transfer all the records in one step?
---> Yes, you can achieve this by writing  Apex class. I am giving code for this please go through once you can under stand easily.
Controller:-

global class SendOldRecord
{
        public void sendrec(list<Account> ls)
        {
            //This list declaration for PartnerNetworkrecords
            List<PartnerNetworkRecordConnection> lstShareRecords = new List<PartnerNetworkRecordConnection>();
            //This list declaration for the Connections with this Organization.
            List<PartnerNetworkConnection> connMap=[select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection
                    where ConnectionStatus = 'Accepted' and ConnectionName='Appshark Software Pvt Ltd'];
            //This for is to loop all the connections
                    for(PartnerNetworkConnection network : connMap) 
                    {    
                        for(Account acc:ls)
                        {
                        //object declaration for PartnerNetwork
                        PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
                        system.debug('Second for loop');
                        newrecord.ConnectionId = network.Id;
                        newrecord.LocalRecordId = acc.id;  
                        newrecord.RelatedRecords = 'Contact';
                        newrecord.SendClosedTasks = true;
                        newrecord.SendOpenTasks = true;
                        newrecord.SendEmails = true;
                        //All the Records are added to the PartnerNetwork
                        lstShareRecords.add(newrecord);
                        }
                   }
              system.debug('List\n'+lstShareRecords);
             //These Records are inserted into Partnernetwork
             //using lstShareRecords.
              insert lstShareRecords;
        }
}
in the case of bulk records , we need to handle them in Batch process,for i have implemented following batch class and pass to list of accounts at every run,
Batch Controller:-
global class RecordBatchApex implements Database.Batchable<Account>
{
global list<Account> start(Database.BatchableContext bc)
{       
    list<account> lstAcc = [select Id from Account];
    return lstAcc;
}

global void execute(Database.BatchableContext bc,List<Account> lstAccount)
{        
system.debug('*******************Execute of Batch Apex***********');
system.debug(lstAccount);
sendoldrecord od=new sendoldrecord();
od.sendrec(lstAccount);
}
//BatchApex Completes
// execution with this finish method
global void finish(Database.BatchableContext BC)
{
system.debug('****Finished*****');
}
Once run that code even from System log,then you can find all the records in business partner login.

2. I want to  insert newly created Account in to partner's organization.
In this Scenario we will go for Apex trigger to create newly inserted account into partner's Organization.

Trigger autoforwardAccount on Account(after insert)
{
String UserName = UserInfo.getName();
String orgName = UserInfo.getOrganizationName();
List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>(
[select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection where ConnectionStatus = 'Accepted']
);
System.debug('Size of connection map: '+connMap.size());
List<PartnerNetworkRecordConnection> prncList = new List<PartnerNetworkRecordConnection>();
for(Integer i =0; i< Trigger.size; i++)
{
Account acc = Trigger.new[i];
String acId = acc.Id;
System.debug('Value of AccountId: '+acId);
for(PartnerNetworkConnection network : connMap)
{
String cid = network.Id;
String status = network.ConnectionStatus;
String connName = network.ConnectionName;
String AccountName = acc.Name;
System.debug('Connectin Details.......Cid:::'+cid+'Status:::'+Status+'ConnName:::'+connName+'AccountName:::'+AccountName);
if(AccountName !=Null)
{
PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
newrecord.ConnectionId = cid;
newrecord.LocalRecordId = acId;
newrecord.SendClosedTasks = true;
newrecord.SendOpenTasks = true;
newrecord.SendEmails = true;
System.debug('Inserting New Record'+newrecord);
insert newrecord;
}
}
}
}

3. Can we insert Contact or Opportunity related for an account,while inserting contact or opportunity ?


Yes, We can, for that we need to trigger on Contact/Opportunity ,here we are inserting contact/opportunity related to an account for that we need to specify account Id also. 
            We PartnerNetworkRecordConnection object for sharing records between salesforce to salesforce.
It contains filed 'ParentRecordId',to that filed we need to assign that account id.I have written trigger on conatct , i am giving code for that,you can implement same thing for opportunity also.
               
 Trigger autoforwardContact on Contact(after Insert)
{  
String  UserName = UserInfo.getName(); 
 String orgName = UserInfo.getOrganizationName();  
List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>(   [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection where ConnectionStatus = 'Accepted']  ); 
System.debug('Size of connection map: '+connMap.size());
 List<PartnerNetworkRecordConnection> prncList = new List<PartnerNetworkRecordConnection>(); 
for(Integer i =0; i< Trigger.size; i++) 

Contact con = Trigger.new[i]; 
String conId = con.Id; 
System.debug('Value of ContactId: '+conId);
for(PartnerNetworkConnection network : connMap)

String cid = network.Id;
String status = network.ConnectionStatus; 
String connName = network.ConnectionName;
String ContactName = con.LastName; 
String Accountid = con.Accountid; 
System.debug('Connectin Details.......Cid:::'+cid+'Status:::'+Status+'ConnName:::'+connName+'ContactName:::'+COntactName);
System.debug('Account ID************'+Accountid);
if(ContactName!= NULL)
{  
System.debug('INSIDE IF');  
 PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();  
 newrecord.ConnectionId = cid;  
 newrecord.LocalRecordId = ConId;  
 newrecord.ParentRecordId= Accountid; // here we are specifying Account ID  
 newrecord.SendClosedTasks = true;   
newrecord.SendOpenTasks = true; 
  newrecord.SendEmails = true;   
System.debug('Inserting New Record'+newrecord);
 insert newrecord; 
}


}        
Using Above Trigger we can Send newly inserted record in to Partner's organization.
I think This may help to any one of us.

Monday 11 July 2011

Insert,Edit,Delete,Clone Records for an object from Vfpage

Hi Friends,
  
I hope below post is very helpful for the learners and help them to understand the basic CRUD operations from VF page.

In the below example, I explained Insert / Edit/Delete /Clone operations on Account object.



Here are the code snippets for VF Page and Controllers.

Vfpage:-
Name :- DML Vfpage
<apex:page Controller="editdeleteCOn" >
<apex:form >
 <apex:sectionHeader title="Edit/Delete" subtitle="Auditing Accounts"/>
 <div align='right'>
 <apex:commandButton value="Insert New" action="{!insertNew}" style="width:150px"/>
  </div>
  <br/>
  <apex:pageBlock >
   <apex:pageBlockTable value="{!lstacc}" var="acc">
     <apex:column >
     {!acc.name}
     <apex:param name="aid" value="{!acc.id}" />
     </apex:column>
     <apex:column value="{!acc.Website}" />
     <apex:column value="{!acc.phone}" />
     <apex:column headerValue="Action" >
      <apex:commandLink value="Edit" action="{!editCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!ecid}"/>
      </apex:commandlink>
      &nbsp;&nbsp;/&nbsp;&nbsp;
      <apex:commandLink value="Delete" action="{!deleteCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!dcid}"/>
      </apex:commandLink>
      &nbsp;&nbsp;/&nbsp;&nbsp;
      <apex:commandLink value="Clone" action="{!cloneCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!ccid}"/>
      </apex:commandLink>
     </apex:column>
   </apex:pageBlockTable>
   <apex:detail subject="{!$CurrentPage.parameters.aid}"/>
  </apex:pageBlock>
  </apex:form>
</apex:page>
Controller:-
public class editdeleteCOn {
 //global declarations
   public String ecid{get;set;} // commandlink edit property
   public String dcid{get;set;} // commandlink delete property
   public String ccid{get;set;} // commandlink clone property
   list<Account> lstacc = new list<Account>();
   list<Account> lstacc1 = new list<Account>();
   // Displaying accounts on vfpage
    public list<Account> getlstacc () {
      lstacc =[select Name,phone,website from Account];
      return lstacc;
    }
    // To redirect to editpage.
     public PageReference editCon() {
       pagereference ref = new pagereference('/apex/dataedit?id='+ecid);
       ref.setRedirect(False);
       return ref;  
    }
    // to delete the selected record
       public pagereference deleteCon() {
        lstacc1 =[Select id,Name from Account where id=:dcid];
        delete lstacc1;
        pagereference ref = new pagereference('/apex/editdelete');
        ref.setredirect(True);
        return ref;  
    }
     // to redirect to insert page.
    public PageReference insertNew() {
    pagereference ref = new pagereference('/apex/accountinsert');
    ref.setRedirect(True);
    return ref;
    }
    // for cloning the records.
    public PageReference cloneCon() {
    account c =  [Select id,Name From account where id =:ccid];
    account cloneaccount = c.clone(false);
    insert cloneaccount;
    pagereference ref = new pagereference('/apex/editdelete');
    ref.setRedirect(True);
    return ref;
    }
}

When you click on Edit link i am redirecting to another vfpage.
Vfpage : dataedit
<apex:page standardController="Account" extensions="savecon">
<apex:form >
  <apex:sectionHeader title="Editing Demo" subtitle="Edit"/>
   <apex:pageBlock tabStyle="Account" >
   <apex:pageBlockButtons location="Bottom">
   <apex:commandButton action="{!save}" value="Save"/>
   </apex:pageBlockButtons>
        <apex:pageBlockSection >
          <apex:inputField value="{!account.Name}"/>
          <apex:inputField value="{!account.Website}"/>
          <apex:inputField value="{!account.phone}"/>
        </apex:pageBlockSection>
   </apex:pageBlock>
</apex:form>
</apex:page>
Controller:savecon
public with sharing class savecon {
    ApexPages.StandardController con;
    public savecon(ApexPages.StandardController controller)
       con=controller;
    }
    public pagereference save()
    {
        con.save();
        return new pagereference(page.editdelete.getUrl());
    }
}
When you click on insert ,i am displaying another page to insert records from there,
Vfpage: accountinsert
<apex:page standardController="Account"  extensions="accountinsertcon">
<apex:form >
  <apex:sectionHeader title="Inserting New" subtitle="Account"/>
   <apex:pageBlock >
      <apex:pageBlockButtons >
      <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection >
     <apex:inputField value="{!account.Name}"/>
     <apex:inputField value="{!account.Phone}"/>
     <apex:inputField value="{!account.Website}"/>
     <apex:inputField value="{!account.AnnualRevenue}"/>
     </apex:pageBlockSection>
   </apex:pageBlock>
</apex:form>
</apex:page>
Controller :accountinsertCon
public class accountInsertCOn {
    ApexPages.StandardController con;
    public accountInsertCOn(ApexPages.StandardController controller) {
    con=controller;
    }
    public pagereference save()
    {
       con.save();
       pagereference ref = new pagereference('/apex/editdelete');
       ref.setRedirect(TRUE);
       return ref;
    }
}
Thank You! I hope This will be useful for one our friends.

Friday 8 July 2011

Generating Random Passwords to Different users.

Hai friends,

I explored on 'How to Generate Passwords Randomly for different users'.

In Apex , we have Crypto class to support encrypt and decrypt mechanism.

Here is the simple logic to generate AES key using crypto class . This key usually uses to encrypt and decrypt the data .

                           Blob blobKey = crypto.generateAesKey(128);
                           String key = EncodingUtil.convertToHex(blobKey);
                           System.debug(key);

Below is the code to generate AES key and sending email to entered email address . 
Controller:-

  public class PasswordGenerator 
{
        public String comments { get; set; }
        public String EmployeeNumber { get; set; }
        public String company { get; set; }
        public String Qualification { get; set; }
        public String Email { get; set; }
        public String Name { get; set; }
         string strPassword ='';
       public List<SelectOption> getQual() {
        List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('--NONE--','------NONE-----'));
        options.add(new SelectOption('MBA','MBA'));
        options.add(new SelectOption('MCA','MCA'));
        options.add(new SelectOption('DEGREE','DEGREE'));
        options.add(new SelectOption('INTER','INTER'));
        options.add(new SelectOption('SCHOOLING','SCHOOLING'));
        return options;
        }
    public static String getPassword(Integer len)
     {
        Blob blobKey = crypto.generateAesKey(128);
        String key = EncodingUtil.convertToHex(blobKey);
        System.debug(key);
        return key.substring(0,len);
     }
    
     public pagereference save()
      {
        String password =PasswordGenerator.getPassword(12);
        Blog_Members__c obj=new Blog_Members__c();
        obj.Name=Name;
        obj.company__c=company ;
        obj.Email__c=Email;
        obj.Employee_Number__c=EmployeeNumber ;
        obj.Comments__c=comments;
        obj.Qualification__c=Qualification ;    
        obj.Password__c = password;
        insert obj;
        sendpassword(Email,password);
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Login Details has been mail to your Registered mail Address .')); 
         company ='';
         Qualification ='';
         EmployeeNumber ='';
         comments ='';
         Email ='';
         Name ='';
         return null; 
      }
      
      public void sendpassword(String Email,String Password)
      {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{Email}; 
        String[] ccAddresses = new String[] {'haribabu.amudalapalli@gmail.com'};
        String Password1 =Password;
        System.debug('hari Testing'+Password1+'Email address'+toAddresses );
        mail.setToAddresses(toAddresses);
        mail.setCcAddresses(ccAddresses);
        mail.setReplyTo('support@acme.com');
        mail.setSenderDisplayName('Salesforce Blog ');
        mail.setSubject('Pass Word From Salesforce Blog');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setPlainTextBody('Your UserName: ' + Email +';/n Pass Word '+Password1 );
        mail.setHtmlBody('Your UserName: ' + Email +'\n Pass Word '+Password1);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     
      } 
  }

Page:-

<apex:page showHeader="false" sidebar="false" Controller="PasswordGenerator" >
<apex:pagemessages />
<apex:form >
<apex:pageBlock tabStyle="Contact" >
<apex:pageBlockButtons location="Bottom">
<apex:commandButton value="Submit" action="{!save}" onclick="success();"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Salesforce Blog Registartion Form" >
Name:<apex:inputtext value="{!Name}"/>
<br/>
Email:<apex:inputtext value="{!Email}" id="email"/>
<br/>
Company:<apex:inputtext value="{!company}"/>
<br/>
EmployeeNumber:<apex:inputtext value="{!EmployeeNumber}"/>
<br/>
Comments about Blog:<apex:inputtextarea value="{!comments}" cols="27" rows="6"/>
<br/>
</apex:pageBlockSection>
</apex:pageBlock> 
</apex:form>              
</apex:page>

Check this once.It's working fine.
      




Thursday 7 July 2011

Chatter On Vfpage

Hai friends,In my last blog, i have explained you objects involved in chatter , data model of chatter and how to query from that objects.In this post i will explain you how to get them on to Vfpage  and chatting from Vfpage.
I am giving code samples,please follow them,by comments you can understand the code.

  Controller:-

public class chatterController {
   public String UserStatus  { get; set; }
   public String profileImageUrl { get; set; 
   public String post { get; set; } 
   public String AddAFeedPost  { get; set; }  
    List<NewsFeed> myfeed = New List<NewsFeed>();
   List<user> lstuser;
   public chatterController ()
   {
        lstuser = [select FullPhotoUrl from User where Id =: UserInfo.getUserId()]; // User profile photo
        profileImageUrl=lstuser[0].FullPhotoUrl;  
   }
    public List<EntitySubscription> GetFollowing()              // Everyone we're following
    {
        List<EntitySubscription> followingES = [
            select id, parentid, subscriberid, parent.name
            from EntitySubscription
            where subscriberid = :UserInfo.getUserId() // user id.
            ];
       return followingES;
    }
    public List<EntitySubscription> GetFollowers()        // All users who are following us
    {   
        List<EntitySubscription> followers = [
            select id, subscriberid, subscriber.name
            from EntitySubscription
            where parentid = :UserInfo.getUserId() // user id.
            ];      
        return followers;
    }
    public void DoUserStatus()
    {
         User user = [select id, CurrentStatus from User where id = :UserInfo.getUserId()];
        user.CurrentStatus = UserStatus;
        update user;
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Status Updated'));
        UserStatus ='';
    }  
    public void AddPost()             // post from vfpage.
    {
          FeedItem fpost = new FeedItem();
            fpost.ParentId = UserInfo.getUserId();
            fpost.Body = AddAFeedPost;
            insert fpost;
         ApexPages.addMessage(new ApexPages.Message(
            ApexPages.Severity.INFO, 'Successfully Posted to Wall'));
        AddAFeedPost = '';
    }
 public List<NewsFeed> NewsFeed()  {                                / Retrieving all feeds form Newsfeed
        List<NewsFeed> myfeed = [SELECT Id, Type, 
                         CreatedById, CreatedBy.FirstName, CreatedBy.LastName,CreatedDate,
                         ParentId, Parent.Name, 
                         Body, Title, LinkUrl, ContentData, ContentFileName,
                             (SELECT Id, FieldName, OldValue, NewValue 
                              FROM FeedTrackedChanges ORDER BY Id DESC), 
                             (SELECT Id, CommentBody, CreatedDate,
                              CreatedBy.FirstName, CreatedBy.LastName
                              FROM FeedComments ORDER BY CreatedDate LIMIT 10),
                             (SELECT CreatedBy.FirstName, CreatedBy.LastName
                              FROM FeedLikes)
                         FROM NewsFeed
                         ORDER BY CreatedDate DESC, Id DESC
                         LIMIT 20];
           return myfeed;
    }

Visualforce page code:-

<apex:page controller="chatterController3" tabStyle="contact" showheader="false">
<Script>
function addComment(recId)
{
alert(recId);
window.showModalDialog('/apex/commentpage?id='+recId ,"dialogWidth:300px; dialogHeight:200px; center:yes");
window.parent.location.reload();
alert(' Comment Added Successfully');
function addLink(recId)
{

alert(recId);
}
</script>
<apex:form >
<apex:pageMessages />
<apex:sectionHeader title="Post to Friends Wall" subtitle="Chatter On Vfpage"/>
<!-- To Post to the wall -->
<apex:pageBlock tabStyle="FEEDItem">
<apex:pageBlockSection title="Post To User Wall">
<table width="150px">
<tr>
<td>
<apex:image id="profileImage" url="{!profileImageUrl}" />
</td>
<td> <apex:outputLabel > Post To Wall:</apex:outputLabel></td><td>
<apex:inputText value="{!AddAFeedPost}" id="status" maxlength="200" size="50" style="padding-bottom: 6px;" />
</td>
<td> <apex:commandButton value="Add A Post" action="{!AddPost}" /> </td>   
</tr>
</table>
</apex:pageBlockSection>
<!-- END-->
<!--User Status Update-->
<apex:pageBlockSection title=" User Status Update" >
<apex:inputText value="{!UserStatus}" id="status" maxlength="600" size="40" style="padding-bottom: 6px;" />
<apex:commandButton value="Update Status" action="{!DoUserStatus}" />  
</apex:pageBlockSection>
<!-- ENd Of User Status Update-->
<!-- List of records,objects,users that the user folowing-->
<apex:pageBlockSection title="User Following" >
<apex:pageBlocktable value="{!Following}" var="f">
<B>  <apex:column value="{!f.parent.name}" headerValue="User Following list" /></B>
</apex:pageBlocktable>
</apex:pageBlockSection>
<!-- End of Followers List-->
<!--Follwers List-->
<apex:pageblockSection title="User Followers">
<apex:pageblockTable value="{!Followers}" var="f">
<apex:column value="{!f.subscriber.name}"  headerValue="Followers List"/>          
</apex:pageblocktable>
</apex:pageblockSection>
<!-- End Of Followers List-->
<!-- Recent Feeds On User Wall-->
<apex:pageblockSection title="Recent Feeds">
<apex:pageBlockTable value="{!NewsFeed}" var="f" style="width:1000px">     
<apex:column width="200" >
<apex:facet name="header">Post By</apex:facet>
<B><apex:outputText value="{!f.Parent.Name}" /></B>
</apex:column>    
<apex:column width="200" >
<apex:facet name="header">Message Body</apex:facet>
<B><apex:outputText value="{!f.Body}" style="font:Oblique"/></B>
</apex:column>  
<apex:column width="200" >
<apex:facet name="header">Created Date</apex:facet>
<B><apex:outputText value=" {0,date,M/d/yyyy h:mm a}">
<apex:param value="{!f.CreatedDate}" />
</apex:outputText></B>
</apex:column> 
<apex:column headerValue="Comments">
<apex:repeat value="{!f.FeedComments}" var="c">
<apex:outputText value="{!c.CreatedBy.FirstName}" id="cfname" style="color:Blue"/>&nbsp;&nbsp;&nbsp;&nbsp; @Said&nbsp;&nbsp;&nbsp;&nbsp;
<apex:outputText value="{!c.CommentBody}" id="comment-repeat"/>
</apex:repeat>
</apex:column> 
<apex:column headerValue="Action" width="200">
<apex:outputlabel value="Comment" onclick="addComment('{!f.id}');" style="color:blue" /> &nbsp;&nbsp;&nbsp;&nbsp;
<apex:outputlabel value="Link" onclick="addLink('{!f.id}');" style="color:Green" />
</apex:column>
</apex:pageBlockTable>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Another Vfpage to Pop up and to add Comment when ever you click on comment:-

<apex:page controller="addComment" showHeader="False">
<script>
function refresh(){
 self.close();
}
</script>
<apex:form >
 <apex:sectionHeader title="Comment" subtitle="Comment To FeedItem"/>
   <apex:pageBlock tabStyle="Contact">
    <apex:pageBlockButtons location="Bottom">
     <apex:commandButton value="Add" Action="{!save}" onclick="refresh()"/>
    </apex:pageBlockButtons>
      <apex:pageBlockSection title="Add COmment">
        <apex:pageBlockSectionItem >
         <apex:outputText ><B>Enter Comment:</B></apex:outputText>
         <apex:inputTextarea value="{!cmttext}" cols="50" rows="5"/>
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
     </apex:pageBlock>
     </apex:form>
</apex:page>

Comment Controller:-

public class addComment {
public String cmttext { get; set; }
Public Id cmdid;
public PageReference save() {
FeedComment fcomment = new FeedComment();
cmdid = ApexPages.currentPage().getParameters().get('id');
fcomment.FeedItemId= cmdid;
System.Debug('IDDDDDDDDDDDDDDDDDDDDD'+cmdid);
System.debug('Comment@@@@@@'+cmttext);
fcomment.CommentBody =cmttext;
insert fcomment;
return Null;
}
}
Execute above code.Its perfectly working and you can start chatting from vfpage.
I think this may helps for any one.


Chatter data Model and objects.

Hai friends , i have explored on the chatter,especially on chatter data model and displaying chatter feeds on Vfpage ,sending comments to feeds from Vfpage.
first i will explain about the chatter objects and chatter data model.
              Feed item is the Basic entity in the chatter,information about the each chatter feed(post) like created date,created by,body,....are stored as Feed item in chatter.Here Feed items are different types  ,they are 
                                   User Profile feed
                                   Entity feed
                                   News Feed
                                   Collaboration Group Feed.
Entity Feed :- In Chatter to follow data ,we need  to enable feed tracking for the desired object and we can specify the fields to know updations for that fields.
 Set up--> App Setup--> customize-->Chatter-->Enable feed tracking.
There you can select object and fields also.(Note you can follow only 20 fields for an object.)
Let us consider you have selected Account object,then entity feeds for that object are stored in Accountfeed(chatter automatically created this).if you want to see all the feeds related to account object you can query data from that records,


Example:-
SELECT Body, Type, Title, CreatedBy.Name
 FROM AccountFeed WHERE ParentId = <Account Record Id>

 in the case of custom object

SELECT Body, Type, Title, CreatedBy.Name
 FROM Employee__Feed WHERE ParentId = < Employee Record Id>
   When you update the record then the updates are stored in to FeedTrackedChanges.this contains both  old and new value of the field for a particular record.We can not query directly from Feed tracked changes,
you can query like,


Example:-
  SELECT Id, (SELECT Id, FieldName, OldValue, NewValue FROM                        
  FeedTrackedChanges ) FROM AccountFeed.                     


NewsFeed:-  Newsfeed forms a sort of aggregate of posts of all users, groups, objects that a particular user following. Which hold all the posts, you can see on user home tab.


Example:-
   SELECT Id, Type, Body, Title, CreatedBy.Name FROM Newsfeed


User Profile feed:-User Profile feed like Newsfeed but it is specific to a particular user.
Example:-
  SELECT Id, Type, Body, Title, CreatedBy.Name FROM UserProfileFeed WITH UserId = <User Id>     
 Collaboration Group feed:- It represents chatter feed for a specific chatter group (private/public).
Example:-
SELECT Id, Type, Body, CreatedBy.Name FROM CollaborationGroupFeed where parentId = <GroupId>
Feed Comment:-
If one user adds a comment to another user post, then a record is created in Feed Comment with reference to feeditemid. We can’t directly query the Feed Comment object, we query from Entity feed.

Example:-
 SELECT Id, (SELECT Id, CommentBody, CreatedDate, CreatedById,
 CreatedBy.FirstName, CreatedBy.LastName
 FROM FeedComments ORDER BY CreatedDate DESC LIMIT 10) 
FROM AccountFeed ORDER BY CreatedDate DESC, Id DESC LIMIT 1


                                                                   chatter Data Model