^ Click Here

Saturday, March 3, 2012

Spring p:namespace example

Continuing with what we learnt in the Spring Basic we will move on to other functionality

for now our example would be same as the basic example i.e.

Person.java
IAnimal.java
Dog.java
Cat.java

Now we will see the p:namespace option in the Spring config file config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"     <!-- This line is required for p:namespace to work -->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="person" class="pkg.Person" p:name="Rahul"> 
    <property name="animal" ref="Dog"/>    
</bean>

<bean id="Dog" class="pkg.Dog" p:name="Doug"/>
<bean id="Cat" class="pkg.Cat" p:name="Jejebel"/>

</beans>

If we run the test now it will print the same "Rahul has a Dog with name Doug"....So as you can see the third line initializes the p namespace function through which we get rid of extra property tag in .xml which made the file heavy.
as for p namespace does the same thing which property tag does, it passes the value to the setter method and it's more readable.

To make it more clear if the Person class has an integer age property, then we can pass avalue through p namespace as p:age="32"

But unfortunately we can't pass reference through p namespace. Hence still where we need to pass the reference we are passing other bean we still have to go with property tag.

Do we have anything where we can pass the reference to other bean without property tag?
The answer fortunately is "Yes" however that's a totally unique functionality and hence much more important than p namespace, It's called "Autowiring"

Tuesday, February 28, 2012

Spring Basic Example

I am providing a very basic example of Spring :-

Firstly I created a "Maven project"

Inside there is a person class person.java

package pkg;

public class Person {
    
    private String name;
    private IAnimal animal;
    
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public IAnimal getAnimal() {
        return animal;
    }
    public void setAnimal(IAnimal animal) {
        this.animal = animal;
    }
    public String toString() {
        return name+" has a "+animal.toString();
    }
}

the Interface IAnimal.java

package pkg;

public interface IAnimal {
    public void play();
}

the animal Dog.java

package pkg;

public class Dog implements IAnimal {
    private String name;
    public void play() {
        System.out.println("Playing with "+name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return " Dog with name "+name;
    }

}

the animal Cat.java

Tuesday, February 21, 2012

Starting/Stopping a timer (stopwatch) in jQuery/javascript

First of all we need to have a HTML container where we can define hour, minute and seconds. the different counter i.e. the values of hour, minute or second are put in div with id counterHour, counterMin and counterSec as can be seen below.
 <div>
Counter : &nbsp;</div>
<div id="counterHour" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; Hours &nbsp;</div>
<div id="counterMin" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; minutes &nbsp;</div>
<div id="counterSec" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; seconds &nbsp;</div>

Also we need a button to start and stop the timer :

<input type="button" id="timer" class="start" value="Start Timer" onclick="check_timer()">
As we can see there is an onclick attribute and check_timer() function is attached to it. Hence in script (<script></script>) tag we will define below functions. 

function check_timer(){
 if($('#timer').hasClass('start')){
  $('#counterSec').fadeOut(500).html(0).fadeIn(500);
  $('#counterMin').fadeOut(500).html(0).fadeIn(500);
  $('#counterHour').fadeOut(500).html(0).fadeIn(500);
  $('#timer').val("Stop Timer");
  timer = setInterval ( "increaseCounter()", 1000 );
  $('#timer').removeClass('start')
 }
 else{
  if(typeof timer != "undefined"){
   clearInterval(timer);  
  }
  $('#timer').val("Start Timer");
  $('#timer').addClass('start')
 }
}
 
function increaseCounter(){
 
 var secVal ;
 var minVal ;
 secVal = parseInt($('#counterSec').html(),10) 
 minVal = parseInt($('#counterMin').html(),10)
 if(secVal != 59)
 $('#counterSec').html((secVal+1));
 else{
  if(minVal != 59){
   $('#counterMin').html((minVal+1)); 
  }
  else{
   $('#counterHour').html((parseInt($('#counterHour').html(),10)+1));
   $('#counterMin').html(0);
  }
  $('#counterSec').html(0);
 }
} 
in check_timer function I am checking if it's start timer or stop timer with the help of class 'start'. and I am alternately starting the set interval and stopping the set interval respectively with changing the value of button.

the logic is pretty simple...set an interval of one second to increase the value of counterSec div. Simultaneously I am checking if it is 60th second to increase the minute counter also if it is 60th minute to increase the hour counter.

Try it here :


Counter :  
0
  Hours  
0
  Minutes  
0
  Seconds  

Friday, February 17, 2012

Spring Security custom login page infinite redirect problem [Solved]

In Spring security we have an option so that we can define our own custom login page instead of one provided by Spring application context framework, this login page is used for determining the ROLE and authentication of certain user using the web application.

However I got into a problem using that when I tried the below security XML configuration :-


    <http>
            <intercept-url pattern="/**" access="ROLE_USER"/>
            <form-login login-page="/login"
            login-processing-url="/static/j_spring_security_check"
            authentication-failure-url="/login?error=t"/>
        </http>
       
        <authentication-manager>
         <authentication-provider>
          <user-service>
           <user name="rahul" password="rahul123" authorities="ROLE_ADMIN,ROLE_USER"/>
          </user-service>
         </authentication-provider>
        </authentication-manager>
       
when I hit the URL it was getting into an infinite redirect request for the login page, Firefox gave an error message like "Firefox has detected that the server is redirecting the request for this address in a way that will never complete".

When I looked into it I could get the real reason of the problem. Actually since the pattern for intercept-url security tag was "/**". It simply meant that any request which start with "/" should be intercepted and authenticated for ROLE_USER. For this authentication purpose Application Context searches for "/login" page but "/login" also start with "/" and hence it is again intercepted and should be authenticated for ROLE_USER for which it would again go for "/login". So it actually is a perfect example of Catch-22 situation. the request was kept redirecting to itself.

Now since we have understood the problem the solution should not be difficult. personally I think giving a pattern as "/**" has dangerous conundrum so instead one should use something like "/home/**" (or any other pattern which should not cover "/login")  for intercept-url so that "/login" should not be authenticated. doing this solved my problem.
     

        <intercept-url pattern="/home/**" access="ROLE_USER"/>

Budding Developer's Ground: SOQL - Learning the parent-child queries for Salesforce 1

Budding Developer's Ground: SOQL - Learning the parent-child queries for Salesforce 1

SOQL - Learning the parent-child queries for Salesforce 1

Well... Lots of time the need arises to show all the opportunities for one contact ( or similar parent child relationships )

Considering it, there are two major part of this first is the query part where we would call all the opportunities for the contacts
 and second is the concept of wrapper class which is actually the mapping of two or more entities.

In salesforce to have a join in a query you must have a parent-child relationship....it's pretty easy to understand that one parent can have many childs.

So Actually there can be two ways of writing a query

(i) Make the child as the central object of the query.
     ex. - [SELECT NAME, Contact.Account.NAME , Contact.Account.somefield FROM Contact];

(ii)Make the parent as the central object of the query.
     ex. - [SELECT NAME, somefield, (SELECT NAME FROM Account.Contacts) FROM Account];

Both the queries above will retrieve same data but in different format and both are used according to the need or requirements (ex - For which entity sorting etc. is needed).

Noticeable things are
  1.  while referring to parent the dot(.) notation is used (contact.account.name in first query).
  2.  while referring to child a subquery is used with the fields it is retrieving .
  3.  in second query the child subquery consist Account.Contacts (and not Account.Contact). Actually here the Contacts does not represent a object type instead it represents the relationship between the Account object type and Contact Object type.
  
Hence one important thing to note is that while referring to a child subquery we must use the name of the relationship and not the object.

P.S you can get the name of the relationship from looking into the 'wsdl' file (type="tns:queryResult" represent child relationship name
to be used in subquery).

Things which wouldn't work :

a> [SELECT * FROM Contact] . There is nothing like '*' in soql, you have to write the fieldnames you want to retrieve.

b> [SELECT id, name, (select name from Account.Contact where createdDate < 2010-01-01), (select name from Account.Contact where createdDate > 2010-12-31) FROM Account]
    You can't use two subqueries for same child relationship while retrieving.


c> [SELECT name,(select name,(select name from Opportunities) from Contacts) FROM Account], the subquery inside another subquery i.e. nested subqueries are not allowed.


   
Due to these reason you would have to frame the query according to your need.
   

This should be enough for the start, We would dwell into parent-child relationship query more in the next part.
   


Saturday, January 28, 2012

Showing Opportunities for each Contact (parent - child) through Map without using Wrapper Class

We can show map from controller on the visualforce page, We also can put one map inside another map or in other words nested map.

With the help of these two factors, I successfully showed the contact and corresponding opportunities without using the wrapper classes. Though it put some restriction however for
the purpose of showing all the opportunities corresponding to each Contact (or any parent - child relationship) it works fine.

The process is simple -
 -I created a map of Contact as key and another map of Opportunity with id as value say A.
 -I used a query which brings all the opportunities for Contacts.
 -Now in a loop get the list of opportunities for each Contact.
 -After checking if there are Opportunities put those Opportunities in a map with id say B.
 -And lastly the Contact and the map B was put into map A.



Visualforce Page :-

 <apex:page controller="MapClass" action="{!getValues}">
<apex:pageblock >
<apex:pageBlockTable value="{!checkMap}" var="con">
    <apex:column value="{!con.Name}"/>
    <apex:column headerValue="Opportunities">
        <apex:dataList value="{!checkMap[con]}" var="opp">
        <apex:outputField value="{!checkMap[con][opp].Name}"/>
        </apex:dataList>
    </apex:column>
    <apex:column value="{!con.Account.Name}"/>
    <apex:column value="{!con.createddate}"/>
   
</apex:pageBlockTable>
</apex:pageblock>
</apex:page>



Apex Class :-

public class MapClass{
  public transient Map<Contact,Map<id,Opportunity>> checkMap{get; set;}
  public void getValues(){
  checkMap  = new Map<Contact,Map<id,Opportunity>>();
  for(Contact s : Database.query('select id, name, Account.name, owner.Name,    createddate, (select id, name from Opportunities) from Contact')){
      List<Opportunity> opLi = s.getSobjects('Opportunities');
      map<id,Opportunity> opMap = new map<id,Opportunity>();
      if(opLi != null){
      for(Opportunity op: opLi){
      opMap.put(op.id,op);   
      }
      }
      checkMap.put(s,opMap);
  }   
}
}

 Last but not the least you can stretch this concept to look what else can be done. feel free to add on it.



Saturday, January 14, 2012

To get a list in different format as HTML / excel / pdf / word in Salesforce

More often than not we need to have an option where we can get a list in an excel or HTML or pdf format....specially for sending it in e-mails.

These formats are standards and presentable hence much desired most often than not.

I did an example where I can show a list of Contacts, Owner name and corresponding Accounts Name with the option to retrieve/download it in excel/HTML/pdf/word format (I tried for picture format also but it didn't work)

Things to notice are

- The file is downloaded with the current date in the name for the ease of distinguishing.

- In the controller the transient variable is being used so that it can show maximum number of records without the view-state error.

- The table is given different background colors for differentiation between rows but each format reads it differently so there is a variation.

Also this is just a raw presentation and a starter.....much can be improved upon this and different functionality or options can be added/modified into it.....

Click here for a demo of this.

The page (visualforce) code -

Wednesday, June 29, 2011

Understanding the CRM workflow Account, Contact, opportunity and Leads

Disclaimer : The ideas are of my own and they might not be technically correct, It's mostly for understanding and not to be relied upon.
Q:What is an Account??

Account is actually an entity with which the concerned is having Business, It could be A company, A firm, A small group.

Q:What is a Contact

Contact is usually a person with whom we are dealing with, A contact is attached to and represent an Account.

Q:What is an Opportunity?

Opportunity is the the available business prospects for the concerned.

Q:What is a Lead?

A lead is one entity which can turn out into a usually long term business Activity. In normal business process a lead when confirmed is converted into an
Account, a Contact and an opportunity.

Now let's understand it by an example.

Suppose I have a business of Stationary products (Paper, pens, pencils etc.). Currently I am providing stationary items in two companies A and B. The person
A-first from the company A asked me for a consignment for his team-members. Also another person A-second from the same company A calls me for another
consignment for the staffs who works under him.

Now here the company A and B are the two Accounts and the person A-first and A-second are the contacts who belongs to the Account A. the consignments which
both the contacts asked for are the two Opportunities.

Now one fine day a friend of mine give me the phone number of a person C-first from the Company C who is probably looking for someone who can provide a
huge consignment.

here I got a Lead with whom I can have a business deal.

I called him and after much haggling I got the order for one more consignment, Then the lead is converted into an Account(C), a contact(C-first) and an
Opportunity (the order for consignment).

In 2 days I provided the consignment for A-first and got the payment Hence the Opportunity from A-first is Closed But I still have two open
opportunities
(from A-second and C-first).

These were the very basic of business process flow in CRM. I hope it would have been useful in clarifying the ideas


Sunday, June 5, 2011

How to get date and datetime as string in desired format in salesforce.

(I am sure there would be other methods, but one which worked for me( I didn't look further). you need to get a date to use in dynamic query.)

//Create a datetime
Datetime dtDate = Datetime.newinstanceGmt(2011,5,21,0,0,0);

// Change the format according to your need and get the date as a string
string dateCh = dtDate.format('yyyy-MM-dd');

string otherdate = dtDate.format('dd-MM-yyyy');

(this was no big deal but if you need to get a datetime for a query(SOQL) this method would be very useful.)

string cdDateCh = dtDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');

ex.-

List = [select name, Account.name from Contact where createdDate > :cdDateCh];