Thursday, 24 April 2014

Thursday, 3 April 2014

program to creating table and inserting records and retriving records dynamically

/*
 * program to create table and insert values dynamically and retrieve all records from table with any   *  number of columns
 */
package jdbcdemos;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 *
 * @author Ramarao
 */
public class JdbcDemo {

    public static void main(String[] args) throws SQLException {
        System.out.println("enter choice");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();

        switch (choice) {
            case 1:
                System.out.println("creating table");
                System.out.println("enter table name");
                String tablename = sc.next();

                System.out.println("how many cloumns u want");

                int colnum = sc.nextInt();
                StringBuffer str = new StringBuffer("create table " + tablename + "(");
                while (colnum != 0) {
                    System.out.println("enter column name");
                    String colname = sc.next();
                    System.out.println("enter column data type with size");
                    String colsize = sc.next();
                    String column = new String(colname + " " + colsize);
                    if (colnum != 1) {
                        //StringBuffer sb= new StringBuffer(column+",");
                        str.append(column + ",");
                    } else {
                        str.append(column);
                    }
                    colnum--;
                }

                str.append(");");
                String sql = new String(str);
                System.out.println(sql);
                //creating dtabase connection
                try {

                    Connection con = DriverManager.getConnection("jdbc:mysql://db4free.net:3306/sriniamz", "srinidb", "test321");
                    System.out.println(con);
                    System.out.println("connection success....");
                    Statement st = con.createStatement();
                    st.execute(sql);
                    System.out.println("table created successfully....");
                    st.close();
                    con.close();
                } catch (Exception e) {
                    System.out.println(e);
                }

                break;
            case 2:
                System.out.println("inserting data");

                try {
                    Connection con = DriverManager.getConnection("jdbc:mysql://db4free.net:3306/sriniamz", "srinidb", "test321");
                    System.out.println(con);
                    System.out.println("connection success....");
                    Statement st = con.createStatement();
                    System.out.println("enter table name");
                    String tblname = sc.next();
                    String selectsql = "select * from " + tblname + ";";
                    System.out.println(selectsql);
                    ResultSet rs = st.executeQuery(selectsql);
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int totalcolnum = rsmd.getColumnCount();
                    System.out.println(totalcolnum);

                    System.out.println("how many records you want to enter");
                    int record = sc.nextInt();
                    while (record != 0) {

                        StringBuffer insstr = new StringBuffer("insert into " + tblname + " values(");
                        for (int i = 1; i <= totalcolnum; i++) {
                            System.out.println("enter value for " + rsmd.getColumnName(i));
                            String value = sc.next();
                            if (rsmd.getColumnTypeName(i) == "VARCHAR") {
                                value = "'" + value + "'";
                                System.out.println(value);
                            }
                            StringBuffer colval = new StringBuffer(value);
                            System.out.println(rsmd.getColumnTypeName(i));

                            if (i != totalcolnum) {
                                insstr.append(colval + ",");
                            } else {
                                insstr.append(colval);
                            }

                        }

                        insstr.append(");");
                        System.out.println(insstr);
                        String insertsql = new String(insstr);
                        st.executeUpdate(insertsql);
                        record--;

                    }
                    st.close();
                    con.close();
                } catch (Exception e) {
                    System.out.println(e);
                }

                break;

            case 3:
                System.out.println("update values");

                break;
            case 4:
                System.out.println("delete values");
                break;
            case 5:
                System.out.println("display table");

                String url = "jdbc:mysql://db4free.net:3306/sriniamz";
                String usrname = "srinidb";
                String pass = "test321";
                StringBuffer sb = new StringBuffer();
                try {
                    Connection con = DriverManager.getConnection(url, usrname, pass);
                    System.out.println(con);
                    Statement st = con.createStatement();
                    Scanner sc1 = new Scanner(System.in);
                    System.out.println("enter tabel name");
                    String table = sc.next();
                    ResultSet rs = st.executeQuery("Select * from " + table);
                    ResultSetMetaData rsmd = rs.getMetaData();
                    String[] strcol = new String[rsmd.getColumnCount()];
                    System.out.println(rsmd.getColumnCount());
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        strcol[i - 1] = rsmd.getColumnName(i);

                    }
                    for (int i = 0; i < strcol.length; i++) {
                        System.out.println(strcol[i]);
                        if (i == strcol.length - 1) {
                            sb = sb.append(strcol[i]);
                        } else {
                            sb = sb.append(strcol[i] + ",");
                        }

                    }

                    String colnames = new String(sb);
                    String sqlquery = "select " + colnames + " from " + table;
                    System.out.println(sqlquery);
                    Statement st1 = con.createStatement();
                    ResultSet rs1 = st1.executeQuery(sqlquery);
                    StringBuffer sub = new StringBuffer();
                    while (rs1.next()) {
                        String concat = null;
                        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                            String record = rs1.getString(i);
                            if (i == rsmd.getColumnCount()) {
                                System.out.print(record);
                            } else {
                                System.out.print(record + ",");
                            }

                        }
                        System.out.println();
                    }
                    rs.close();
                    st.close();
                    con.close();

                } catch (Exception e) {
                    System.out.println(e);
                }

                break;

            default:
                System.exit(0);
        }

    }

}

Monday, 10 March 2014

about calander class in java

International Calendars in Java

IBM Center for Java Technology

Over the last few years, many programmers have had a growing awareness of international issues, both in Java and in other languages. The software industry and the economy as a whole are becoming much more global, and there is an increasing need for applications that can function properly in more than one language and country. In addition, many programming toolkits such as the Java Class Libraries, the Win32 and Macintosh API’s, POSIX, etc., have fairly extensive international support built in, which makes writing an internationalized application much easier than it used to be.
While these API’s are all designed differently, at their core they provide a similar set of functionality. There are character converters that transform Unicode to legacy code pages, and vice-versa. There are sorting routines or collator objects that can be used for language-sensitive string comparison. There are facilities for word- and line-break detection in different languages. Finally, there are ways of formatting numbers, dates, times, and currencies for different languages and countries.
The date, time, and number formatters are necessary because most countries have different conventions for displaying this data. For example, an American English speaker would write the date 1/1/2000 AD (or 1/1/2000 CE) as "Saturday, January 1, 2000." A British English speaker might write "Saturday, 1 January 2000" instead. And a French speaker would write "samedi 1 janvier 2000". Any self-respecting international library can handle this for you. In Java, you’d use the class java.text.DateFormat to do the work.
Still, I suspect that even today a lot of programmers would look at the title of this article: "International Calendars", and wonder just what those two words have to do with each other. Dates, sure. But calendars? Though the topics might not seem linked at first, the connection is fairly obvious once you think about it.
Consider what should happen when a Hebrew speaker in Israel is using your program. The same date we discussed above, 1/1/2000 AD, would be displayed as "תבש 23 תבט 5760" or "Saturday 23 Tevet 5760". Not only are the strings different, the numbers are as well.
Though it comes as a surprise to many Americans, the official calendar in Israel is the Hebrew calendar, not the Gregorian one that we use in most of the Western world. The Hebrew calendar, as well as many others such as Hijri (Islamic), Hindu, Buddhist, and Japanese, all number the years differently. Many of them, including the Hebrew, also have a different system for calculating months, which leads to 1/1/2000 AD being "תבש 23", or "Tevet 23", rather than January 1.
All of this means that internationalization of dates and times requires more than just a different table of strings for each language. A program that naïvely assumes that the Gregorian calendar applies everywhere will be hopelessly wrong in countries that use a different calendar rather than just a different language.
In this article, I’ll discuss the Java Class Library facilities that allow you to manipulate and display dates and times. Next, I’ll show how you can extend the Java calendar classes to support calendars that are not built in to the JDK. Finally, I’ll discuss some free classes from IBM that support the Buddhist, Hebrew, Hijri, and Japanese Imperial calendars.
A brief history
First, let me jump back to JDK 1.0 for a moment. The first release of Java had relatively poor support for international dates and times, with java.util.Date and its toString method the only real tools at your disposal. The situation in the rest of Java was similar. It had the beginnings of international support, because a Java char is stored as a Unicode character. But that's all. You couldn't enter or display non-Latin characters, and there were no facilities for language-sensitive formatting, sorting, and so on.
The management of Sun and IBM found a way to fix this problem for JDK 1.1. Java was missing international support. But IBM’s Taligent subsidiary had great international technology, talented engineers -- including Dr. Mark Davis, president of the Unicode Consortium -- and a location about 100 yards away from Sun’s JavaSoft division in Cupertino, California. Thus a partnership was born. IBM arranged for Taligent’s Text and International group to contribute international classes into Sun’s JDK in order to make Java powerful enough for real-world business applications.
Taligent, in collaboration with Sun's internationalization engineers, provided the new java.text package, plus a number of new classes in java.util. This included the date- and time-related classes DateFormat,SimpleDateFormatCalendarGregorianCalendarTimeZone, and SimpleTimeZone. I’ll discuss these classes in turn, starting with the old Date class.
Date
The java.util.Date class has been part of Java since JDK 1.0. Each instance of Date represents a particular instant in time, stored as a long number of milliseconds since January 1, 1970 AD, 00:00 GMT. To construct a Date, you would typically use the constructor:
Date(int year, int month, int date)
or one of its variants that takes additional arguments such as hours, minutes, seconds, etc. In addition, there is a constructor whose argument is a String such as "Sat Aug 12 1995 13:30:00 GMT".
In JDK 1.0, and even today, these methods all work as advertised. If you execute the following code:
Date d = new Date(99, 1, 1);

String s = d.toString();
the value of s will be "Mon Feb 1 00:00:00 PDT 1999".
There are a few obvious problems here. The most blatant is that the year argument to the constructor is only two digits, with 1900 assumed to be the origin. This is a huge Y2K problem, because there’s no way to specify a date before 1900 or after 1999. There’s also no obvious way to fix this. Sun can’t change the meaning of the first parameter, because that would break existing code. Adding a Y2K-safe override would be difficult too, since that would require the overload to have different argument types.
The next problem is the toString method. The JDK 1.0 documentation stated that the string it returns was always of the form "Sat Aug 12 1995 13:30:00 GMT", with US English day and names and time zone abbreviations. Again, there was no way to change this in a later release. Once the documentation, which is effectively the specification for the Java Class Libraries, guarantees a certain behavior, it can't be changed without the danger of breaking existing applications.
Finally, take another look at the Date constructor in the code snippet above:
Date d = new Date(99, 1, 1);
Notice that we passed in "1" for the month and day, but the resulting date was February 1st. Since arrays in Java and C are 0-based, and since month numbers are often used as an index into an array of strings, the original designers of Java decided to make the month numbers 0-based. So January is month 0, February is month 1, and so on. Unfortunately most people, even programmers, think of January as the 1st month of the year, not the 0th, so this choice has led to a great deal of confusion.
When it was time to work on JDK 1.1, we were faced with a decision: What should we do about Date? Because of the problems I discussed above, IBM and Sun decided that Date was so broken that it couldn't be fixed and decided to replace it instead. But since Date was trying to do so many different things -- date formatting, calendar calculations, and time zones, we decided to replace it with several different classes.
Date Formatting
The first of these new classes is DateFormat. As I mentioned above, Date's String constructor and its toString method had two problems: the strings were in a fixed format and they were always in English. DateFormatsolves both of these problems.
The job DateFormat and its concrete subclass SimpleDateFormat is to convert from a Date object to a String and vice-versa, and to do it properly for all of the locales that Java supports. To format a date and time for the current locale, the code is fairly simple:
Date d = new Date(1999, 0, 1);

DateFormat f = DateFormat.getDateTimeInstance(

                               DateFormat.FULL,  // Date style

                               DateFormat.FULL); // Time style

String s = s.format(d);
If you run this on a US English system, the result will be "Friday, January 1, 1999 00:00:00 AM PST".
So far, this just seems like an expensive way of spelling Date.toString. But you get something for the extra effort: internationalization. If you change the second line of code to this:
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.FULL,

                                              DateFormat.FULL,

                                              Locale.FRANCE);
the result will appear in French: "venredi 1 janvier 1999 00:00:00 GMT-08:00".
DateFormat also solves the fixed-format problem. The examples above uses a "FULL" date/time formatter. If you want to be a bit more concise, you can use DateFormat.MEDIUM, which gives the result "Jan 1, 1999 00:00:00 AM" for English. Similarly, DateFormat.SHORT gives "1/1/99 00:00 AM."
If you want to see just the date in your output, not the time, the solution is also simple -- call getDateInstance instead of getDateTimeInstance :
Date d = new Date(99, 0, 1);

DateFormat f = DateFormat.getDateInstance(DateFormat.FULL);

String s = s.format(d);
and the result will be "January 1, 1999."
Now, remember the Date constructor that takes a String. That constructor had the same problems as toString , but in reverse: it required a fixed format and it assumed the string would be in English. DateFormat solves these problems too, because it doesn’t just format dates; it parses them. For example, consider the following code:
DateFormat f = DateFormat.getDateInstance(DateFormat.FULL,

                                          Locale.FRANCE);

Date d = f.parse("venredi 1 janvier 1999");
The Date object, d, will end up referring to 1/1/1999. All of the other points I discussed above apply to parsing as well as to formatting: you can request a particular locale, choose shorter or longer formats, etc.
TimeZone
Many of the DateFormat examples I showed above included time zones in their output. In JDK 1.0, all of Java's time zone logic was baked into Date.toString. It assumed that you always wanted dates displayed using the current default time zone, and that you wanted the US English abbreviations for the time zone names. This was fixed in JDK 1.1 as well, with the addition of the new class java.util.TimeZone.
TimeZone and its concrete subclass SimpleTimeZone are relatively low-level classes that encapsulate the relationship between local clock time and Greenwich Mean Time. You can use them to convert from GMT to local time and back as well as to determine whether daylight savings time is in effect. The other classes use TimeZone in their time-related calculations, and many of them expose the time zone as a property that you can get and set.
Here's a simple example. Say that you want to display the same date we've been using in all of our examples, but that you want to force it to be displayed in GMT, regardless of the time zone you're running in. The code would look like this:
Date d = new Date(99, 0, 1);

DateFormat f = DateFormat.getDateTimeInstance(DateFormat.FULL);

f.setTimeZone(TimeZone.getTimeZone("GMT"));

String s = s.format(d);
The formatter will now use GMT, so the result will be something like " Friday, January 1, 1999 08:00:00 AM GMT ". Note that the time zone is different, and that the time of day is 08:00, since GMT is 8 hours ahead of PST.
In JDK 1.1, there was one problem with the way that DateFormat used TimeZone. Let's jump back to this example for a moment:
Date d = new Date(99, 0, 1);

DateFormat f = DateFormat.getDateTimeInstance(DateFormat.FULL,

                                              DateFormat.FULL,

                                              Locale.FRANCE);

String s = s.format(d);
As I mentioned above, you'd expect the result to be "venredi 1 janvier 1999 00:00:00 GMT-08:00" if you were running your computer in the Pacific time zone. However, in JDK 1.1.5 and earlier, the result would actually be "venredi 1 janvier 1999 09:00:00 CEST". CEST is "Central European Standard Time", the time zone used in Paris, which is one hour ahead of GMT. Rather than using the system's default time zone, DateFormat was using the first time zone it could find for the locale you requested, in this case Locale.FRANCE. This caused no end of confusion, since it was almost never what programmers expected.
Fortunately, there was a simple workaround for this problem. To force a DateFormat to use the default time zone, you just do this:
DateFormat f = . . . .;

f.setTimeZone(TimeZone.getDefault());
In JDK 1.1.6 we fixed this problem, and a newly-created DateFormat object always uses the default time zone. If you need a different time zone, you can always call DateFormat.setTimeZone to request the one you want.
Calendar
Now that I've given a quick tour of the other date-related classes that were new to JDK 1.1, I can go on to the meat of this article: java.util.Calendar. As an introduction, let's revisit a code snippet from our discussion of Date :
Date d = new Date(99, 1, 1);
In this example, the constructor arguments are interpreted in only one way: February 1, 1999 AD, in the Gregorian calendar. There's a similar problem with Date methods such as getDaygetMonthgetYear, etc. But as I described in the introduction, some countries use different calendars: Hebrew, Hijri, or whatever. A fully-internationalized Java application needs to be able to support multiple calendar systems, not just the Gregorian one.
Since the Java Class Libraries are object-oriented, the obvious solution to this problem is to create an abstract class that represents a generic calendar, with concrete subclasses for specific calendar systems. And that's just what we did. JDK 1.1. included a new abstract class, java.util.Calendar, which provides a generic API for calendar operations. It also included one concrete subclass, which as you might guess is GregorianCalendar.
Calendar has a number of abstract methods that parallel the old, deprecated get methods of Date. For example, imagine that you want to find out what year it is. With the old Date API, the code would look like this:
int year = new Date().getYear();
With Calendar, you do this instead:
int year = Calendar.getInstance().get(Calendar.MONTH);
The call to getInstance creates a Calendar that is appropriate for the current locale, and the call to get returns the current value of the calendar's MONTH field. Calendar provides constants for about fifteen fields, including YEAR,DAY_OF_MONTHDAY_OF_WEEKWEEK_OF_YEAR, and many others. These constants are all interpreted in terms of the calendar system that your Calendar object represents, so if you have a Hebrew calendar object, you'll get the Hebrew month, not the Gregorian one.
If you're wondering how this works, remember that Calendar is an abstract class. Each time that get is called, the calendar checks to see if the fields are up to date. If they are not, it calls the abstract, protected methodcomputeFields. Each subclass overrides this method to perform the calculations appropriate for that calendar system. For example, GregorianCalendar has a computeFields method that performs the standard Gregorian calculations.
Calendar.get replaces the deprecated get methods on Date, but what about the constructor? That functionality is provided by constructors on the concrete Calendar subclasses. If you want to construct a Calendar set to January 1, 2000, you write:
Calendar c = new GregorianCalendar(2000, Calendar.JANUARY, 1);
This solves the problem neatly. You know exactly which calendar system will be used to interpret the year, month, and day that you've specified: the calendar that you're instantiating. If someone has input a Hebrew date, and you have a HebrewCalendar class, the code is fairly obvious:
Calendar c = new HebrewCalendar(5760, HebrewCalendar.TEVET, 23);
January is still Zero
You would think that when we deprecated most of Date and added the new Calendar class, we would have fixed Date's biggest annoyance: the fact that January is month 0. We certainly should have, but unfortunately we didn't. We were afraid that programmers would be confused if Date used zero-based months and Calendar used one-based months. And a few programmers probably would have been. But in hindsight, the fact that Calendar is still zero-based has caused an enormous amount of confusion, and it was probably the biggest single mistake in the Java international API's.
When you're using Calendar or any of its subclasses, it's usually best not to use raw numbers in Calendar calls unless you just can't avoid it. Instead of writing code like this:
Calendar c = new GregorianCalendar(2000, 0, 1);
write this instead:
Calendar c = new GregorianCalendar(2000, Calendar.JANUARY, 1);
This takes a bit longer to type, but it's a lot less error-prone.
Add and Roll
One aspect of Calendars that wasn't addressed at all in Date was calendar manipulation. For example, imagine that you want to determine what the date will be one month in the future. With the old API, you had to do an awful lot of work on your own: call getMonthgetYear, and getDate, add one to the month, see if it wrapped to a new year, make sure the day of the month is still in bounds (remembering those leap years!) and so on. Not only is this a hassle, it's not internationalized. Other calendar systems have a different number of days per month, different (and possibly variable) months per year, different leap year calculations, and so on.
Calendar and its subclasses solve this problem for you, with their add and roll methods. If you want to add one month to the current date, you only need two lines of code:
Calendar c = Calendar.getInstance();

c.add(Calendar.MONTH, 1);
As you'd expect, the add method adds the given number to the field that you specify. It knows about all of the rules for the calendar system, so code like this will work properly.
GregorianCalendar c = new GregorianCalendar(1999, Calendar.JULY, 29);

c.add(Calendar.MONTH, 7);

String s = DateFormat.getInstance().format(c.getTime());
The result of this calculation will be February 29, 2000. GregorianCalendar.add knows that when the month passes 11 (December) it should roll back to 0. It also knows that February 29, 2000 is a valid date, using the complicated rules that it is a leap year because it's divisible by four, except it isn't because it's divisible by 100, except it is because it's divisible by 400.
Closely related to add is the roll method. This method is handy when you want to implement a user interface that "rolls" from the end of a month back to the beginning of the same month, or to do the same thing for weeks or years. The usage is almost identical to add:
GregorianCalendar c = new GregorianCalendar(1999, Calendar.JULY, 29);

c.roll(Calendar.DAY_OF_MONTH, 6);
The result will be July 4, 1999. If roll just added 7 to 29 it would get 33, which is past the end of July. Add would handle this by continuing on into August, ending up on August 4th. But roll is different. It wraps back to the beginning of July and end up on July 4th.
Locale-Specific Calendar Properties
If you thought we'd now solved all possible calendar internationalization problems, you'd be incorrect. Even within a single calendar system, such as Gregorian, there are a few properties that can differ from one country to the next. As an example, here are the US and French versions of the calendar for July, 1999:
United States
Sun
Mon
Tue
Wed
Thu
Fri
Sat
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


France
lun
mar
mer
jeu
ven
sam
dim
   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 

Notice that in France, the first day of the week is Monday (or lundi), while in the United States it is Sunday. If you're writing an application that displays calendars graphically, you need to take this into account. Java provides the method Calendar.getFirstDayOfWeek to handle this. When you create a calendar, you can specify the locale you're interested in:
Calendar c = Calendar.getInstance(Locale.FRANCE);
and then call getFirstDayOfWeek to find out how to draw it:
int d = c.getFirstDayOfWeek();
A related method is getMinimalDaysInFirstWeek, which tells you how long a week has to be to qualify as the "first" week of the month. In the US calendar shown above, is the first week of July the week that starts on July 5, or the previous one that starts on June 27? According to Java's locale data it's the latter, because getMinimalDaysInFirstWeek returns 1.
Creating your own Calendars
All of the international calendar features I've talked about so far are great. However, there's a catch that limits the amount of calendar internationalization that you can actually do. Both JDK 1.1 and Java 2 only provide one concrete subclass of CalendarGregorianCalendar. The traditional calendars used in other countries are not yet supported.
However, all is not lost. It entirely possible to create your own subclasses of Calendar that support different calendar systems. I've written classes that support the Buddhist, Hebrew, Hijri, and Japanese Imperial calendars, and I want to share some of that knowledge here.
When you look at the Calendar class, you'll notice that it has 11 abstract methods: add, after, before, equals, getMinimumgetMaximumgetGreatestMinimumgetLeastMaximumrollcomputeTime, and computeFields. Implementing your own calendar subclass requires that you override all of these methods to provide an implementation that's specific to your calendar system. These methods can be divided into three basic groups.
The first group, the minimum and maximum functions, are the easiest so these are usually the ones that I implement first. The first two, getMinimum and getMaximum, tell you the largest allowable range for each field, whilegetLeastMaximum and getGreatestMinimum , tell you the smallest range for the field. For example, the DAY_OF_MONTH field of GregorianCalendar has a minimum and maximum of 1 and 31, but a greatest minimum and least maximum of 1 and 29. Implementing this is easy. Since the result is a constant, you can just store it in a table. The methods almost always ends up looking like this:
public int getMinimum(int field) {

    return minMax[field][0];

}
The real heart of a calendar class consists of its computeFields and computeTime methods. The first, computeFields, calculates the values of all of the fields (year, month, day, etc.) from the absolute time, which is represented as the number of milliseconds since January 1, 1970. Conversely, computeTime uses the field values to calculate the absolute time.
These two methods are usually quite complicated, because they must implement the calendar system's rules very precisely. The details for a real calendar are way beyond the scope of this article, so I've invented a very simple calendar that we can experiment with. It has 360 days per year, divided into 12 months of 30 days each, with no leap years. There are seven days per week, just like our calendar, and the day 1/1/1 in this calendar was a Saturday. Based on this simplification, I can offer a few generalizations.
First, your calculations will usually be based on an "epoch" date on which the calendar started. Usually you'll want this to be the 0th day of your calendar, that is the day before the first day of year 1. You should define a constant that specifies the epoch in milliseconds since 1/1/1970 AD. I'll start our example calendar on the same day the Hebrew calendar started, just because I have the constant handy:
private static final long EPOCH_MILLIS = -180799862400000L;
You'll also need a few constants for the number of milliseconds in a second, minute, hour, etc:
private static final long SECOND_MS = 1000;

private static final long MINUTE_MS = 60 * SECOND_MS;

private static final long HOUR_MS   = 60 * MINUTE_MS;

private static final long DAY_MS    = 24 * HOUR_MS;
Next, you'll want to get used to modular arithmetic, because you'll be doing a lot of it. Many of the calculations will be based on the number of days since the epoch, so you should calculate that first:
long absDay = (time - EPOCH_MILLIS) / DAY_MS;
Once you have that number, it's easy to calculate the year, month, and day:
int year  = (int)(absDay / 360) + 1;

int month = (int)((absDay / 30) % 12) + 1;

int day   = (int)(absDay % 30) + 1;
Of course, the calculations are a lot more complicated for real calendar systems, what with the variable month and year lengths, leap years, and the other complex interdependencies such as the "postponement rules" in the Hebrew calendar. There are a number of good references on this subject, including some web sites you can find with most search engines. But my favorite resource is the book Calendrical Calculations, which is listed in the references at the end of this article.
Real Code
If you'd like to see some real Java classes that implement non-Gregorian calendars, pay a visit to http://www.alphaWorks.ibm.com/tech/calendars. The "International Calendars" package you'll find on that page supports the Buddhist, Hebrew, Hijri, and Japanese Imperial calendars. It includes Java ResourceBundle files containing translated strings for these calendars in a number of different languages, as well as some utility methods for formatting dates as strings using non-Gregorian calendars.
I hope this article has given you a good feel for the things that you can do with calendars in Java. Though it has its warts, Java's calendar framework is the most powerful one I've seen in any major operating system or application framework.
Acknowledgements
Alan Liu, the IBM engineer responsible for the time and date classes in the JDK, was very helpful while I was writing this paper.
References
Calendrical Calculations, by Nachum Dershowitz and Edward M. Reingold (Cambridge University Press, 1997) has excellent descriptions of calendar algorithms in general as well as detailed algorithms for all of the calendar systems in common use today.
The Java Class Libraries, 2nd Edition, vol. 1, by Chan, Lee, and Kramer (Addison-Wesley, 1998) has a nice description of Calendar and GregorianCalendar.
Making your Java/C++/C Applications Global, at www.ibm.com/java/education/international-unicode/unicode1.html is a good overview of some of the issues involved in writing global applications.

Thursday, 20 June 2013

salseforse interview questions-2



1. What is Apex

Ans: It is the in-house technology of salesforce.com which is similar to Java programming with object oriented concepts and to write our own custom logic.




2. What is S-Control ?
Ans: S-Controls are the predominant salesforce.com widgets which are completely based on Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.




3. What is a Visualforce Page ?
Ans: Visualforce is the new markup language from salesforce, by using which, We can render the standard styles of salesforce. We can still use HTML here in Visualforce. Each visualforce tag always begins with “apex” namespace. All the design part can be acomplished by using Visualforce Markup Language and the business logic can be written in custom controllers associated with the Page.




4. Will Visual force still supports the merge fields usage like S-control ?
Ans: Yes. Just like S-Controls, Visualforce Pages support embedded merge fields, like the {!$User.FirstName} used in the example.




5. Where to write Visualforce code ?
Ans: You can write the code basically in 3 ways.

1.        setup->App Setup->Develop->Pages and create new Visulaforce page.

2.        Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, https://ap1.salesforce.com/apex/MyTestPage. you will find the Page editor at the bottom of the page. You can write you page as well as the controller class associated with it, there it self.

3.        Using EclipseIDE you can create the Visulaforce page and write the code.




6.What are Apex Governor Limits?

Governor limits are runtime limits enforced by the Apex runtime engine. Because Apex runs in a shared, multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that code does not monopolize shared resources. Types of limits that Apex enforces are resources like memory, database resources, number of script statements to avoid infinite loops, and number of records being processed. If code exceeds a limit, the associated governor issues a runtime exception.
7. How to create and host S Control in Salesforce ?

To demonstrate this, lets consider an example of Google Map.
Lets create a S-Control for the Google Map.
Now let’s first create a new S-Control:
  1. Click on “Setup” which is located on the top right corner of the force.com page.
  2. Expand “Develop” item and click on “S-Controls”
  3. Hit “New Custom S-Control”
  4. Provide a Label “Google Map” and a description is you wished to
  5. The Type should be HTML since we want to create a HTML, Google API mash up
  6. Now it is time to enter the code for the S-Control
S-Control in Salesforce.com
1<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
2<head>
3<meta http-equiv="content-type" content="text/html; charset=utf-8" />
4<title>Google Maps JavaScript API Example: Advanced Directions</title>
5<link href="/dCSS/Theme2/default/common.css" type="text/css" media="handheld,print,projection,screen,tty,tv"
6rel="stylesheet">
7<link href="/dCSS/Theme2/default/custom.css" type="text/css" media="handheld,print,projection,screen,tty,tv"
8rel="stylesheet">
9 
11type="text/javascript"></script>
12 
13<script src="/js/functions.js" type="text/javascript"></script>
14 
15<script type="text/javascript" src="/soap/ajax/13.0/connection.js"></script>
16 
17<style type="text/css">
18body {
19font-family: Verdana, Arial, sans serif;
20font-size: 11px;
21margin: 2px;
22}
23table.directions th {
24background-color:#EEEEEE;
25}
26 
27img {
28color: #000000;
29}
30</style>
31 
32<script type="text/javascript">
33 
34var map;
35var gdir;
36var geocoder = null;
37var addressMarker;
38var dirFrom = '{!$Request.from}';
39var dirTo = '{!$Request.to}';
40var mapLocale = ""
41var SControlID = '{!$Request.lid}';
42var SFrameIC = '{!$Request.ic}';
43 
44 
45function initValues()
46{
47mapLocale = "en_US";
48 
49setInputFields(dirFrom,dirTo);
50}
51 
52function setInputFields(from, to)
53{
54window.document.getElementById("fromAddress").value = from;
55window.document.getElementById("toAddress").value = to;
56}
57 
58 
59function initialize()
60{
61initValues();
62 
63if (GBrowserIsCompatible()) {
64map = new GMap2(document.getElementById("map_canvas"));
65map.addControl(new GSmallMapControl());
66map.addControl(new GMapTypeControl());
67gdir = new GDirections(map, document.getElementById("directions"));
68GEvent.addListener(gdir, "load", onGDirectionsLoad);
69GEvent.addListener(gdir, "error", handleErrors);
70 
71setDirections(dirFrom, dirTo, mapLocale);
72}
73}
74 
75function setDirections(fromAddress, toAddress, locale) {
76if ((fromAddress) && (toAddress))
77gdir.load("from: " + fromAddress + " to: " + toAddress,
78{ "locale": locale });
79}
80 
81function handleErrors()
82{
83if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
84alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
85else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
86alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
87 
88else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
89alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
90 
91// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) <--- Doc bug... this is either not defined, or Doc is wrong
92// alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
93 
94else if (gdir.getStatus().code == G_GEO_BAD_KEY)
95alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
96 
97else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
98alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
99 
100else alert("An unknown error occurred.");
101 
102}
103 
104function onGDirectionsLoad(){
105// Use this function to access information about the latest load()
106// results.
107 
108// e.g.
109// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
110// and yada yada yada...
111}
112</script>
113 
114</head>
115<body onload="initialize()" onunload="GUnload()">
116<div style="background-color: #CCCCCC">
117<form action="#" onsubmit="setDirections(this.from.value, this.to.value, this.locale.value); return false">
118<table>
119<tr>
120<th align="right">
121From:&nbsp;</th>
122<td>
123<input type="text" size="25" id="fromAddress" name="from" value="" /></td>
124<th align="right">
125&nbsp;&nbsp;To:&nbsp;</th>
126<td align="right">
127<input type="text" size="25" id="toAddress" name="to" value="" /></td>
128<th align="right">
129Language:&nbsp;</th>
130<th align="right">
131<select id="locale" name="locale">
132<option value="en" selected="selected">English</option>
133<option value="fr">French</option>
134<option value="de">German</option>
135<option value="ja">Japanese</option>
136<option value="es">Spanish</option>
137</select>
138</th>
139<td>
140<input name="submit" type="submit" value="Get Directions!" /></td>
141</tr>
142</table>
143</form>
144</div>
145<div style="border-width: 1px; border-color: #000000; border-style: solid;">
146<div style="overflow: auto; width: 99.5%; height: 380px">
147<table class="directions" style="width: 100%; height: 100%">
148<tr>
149<td valign="top" style="width: 275px;">
150<div id="directions" style="width: 275px; background-color: #ffffff;">
151</div>
152</td>
153<td valign="top">
154<div id="map_canvas" style="width: 100%; height: 375px; background-color: #ffffff;">
155</div>
156</td>
157</tr>
158</table>
159</div>
160</div>
161</body>
162</html>




8. Difference between Sandbox and Development environment?
A test environment for salesforce.com is crucial to change control. Salesforce.com provides the tools needed to test anything in a test environment before you implement it in your live instance. You can either test in a Sandbox environment or in a Developer environment. What is the difference? I will share what I know…
Sandbox
The salesforce.com Sandbox environment is an exact copy of your salesforce.com instance. You can copy your live instance to a sandbox environment (but you have to perform manually from sandbox to developer edition) where you can test any changes, implementations, AppExchange apps or updates. It can also be your hands-on training environment without risking your live data.
You can either copy your configuration and data into a sandbox environment or just the configuration. It acts exactly like your live instance, but be careful if you have workflow rules or automations because they will work in the sandbox as well.
I know that this sounds wonderful and if you don’t have it, you are dying to know how to get it. The problem is the cost. If you are on Unlimited Edition, then cost is not a problem because it comes included. But for Enterprise, Professional or Group Editions, you have to pay… and the price is hefty; anywhere between 25k-50k per year. For a lot of companies, that is more than they are paying for their live salesforce.com instance. So how do you test salesforce.com without Sandbox?  It is always suggested to develop application in sandbox instance then go for LIVE.
Developer Edition
Developer Edition was an edition created for development of integrations and apps, specifically for the AppExchange. It is also a great tool for testing/training in salesforce.com. What makes this a great tool is the fact that it is free. Anyone can get a Developer Edition of salesforce.com. It is a standard Enterprise Edition with very limited storage space. You cannot copy your configuration or data onto the Developer Edition, but you can customize it to match your instance’s look and feel. Once it is customized, you can use it for training, testing or anything else you want. It takes a little bit of work, but you can make it act and feel just like your live instance. The work is well worth it for the free price.
To get a copy of Developer Edition for yourself or your company go here. Play around with it. Get apps from the AppExchange. Do anything and everything that you have been scared to do your live system. If you come up with a clever way of using the system, post it on AppExchange and share your knowledge.
 

13. When you can’t add Time dependent action in Workflow rule?
You can’t add time-dependent actions to a rule if you choose Every time a record is created or edited.
 
Workflow is the automation of the following types of actions based on your organization’s processes:
  • Tasks – Assign a new task to a user, role, or record owner.
  • Email Alerts – Send an email to one or more recipients you specify.
  • Field Updates – Update the value of a field on a record.
  • Outbound Messages – Send a secure configurable API message (in XML format) to a designated listener.
For example, workflow can automatically:
  • Assign follow-up tasks to a support rep one week after a case is updated.
  • Send sales management an email alert when a sales rep qualifies a large deal.
  • Change the Owner field on a contract three days before it expires.
  • Trigger an outbound API message to an external HR system to initiate the reimbursement process for an approved expense report.
To create workflow rule, go to App Setup | Workflow & Approvals | Workflow rules and click on new Workflow rule.
Salesforce creating Workflow rule step 1
Salesforce creating Workflow rule step 1
Step 1 in creating workflow rule is selecting the object, on which the workflow will be created.

in step 2, Evaluation criteria have three options to choose:
  • When a record is created, or when a record is edited and did not previously meet the rule criteria: Choose this option to include new records and updates to existing records, unless the rule just ran and still meets the rule criteria. The rule is not re-triggered on edits that do not affect rule criteria. For example, if setting an opportunity rating to “Hot” causes the rule to run, with this option, the rule will run again only if the rating changes, then changes back to “Hot”—no matter how many times you edit the object.
  • Only when a record is created: Choose this option to ignore updates to existing records.
  • Every time a record is created or edited: Choose this option to include new records and updates to existing records and repeatedly trigger the rule, even if the record still meets the criteria. You cannot add time-dependent actions to the rule if you choose Every time a record is created or edited.
Note : You can’t add time-dependent actions to a rule if you choose Every time a record is created or edited.
Salesforce creating Workflow rule step 2
Salesforce creating Workflow rule step 2
So, in step 2 basically we create a criteria when the rule should run.
Salesforce creating Workflow rule step 3
Salesforce creating Workflow rule step 3
In step 3, we can specify the action what should happen if workflow criteria meets.
In this case, i have selected New Email Alert, below screen shot is self explanatory about the process.
Salesforce add email alert in workflow action
Salesforce add email alert in workflow action
We have to select the recipients for the email, in our case Email field have the email address of the student. We have also selected the newly created email template “Welcome to shivasoft”.
In this tutorial, we have covered how to create the Workflow rule criteria and action in salesforce.com.
In next part of tutorial, we will see how to create the trigger for our application.



14. What are the types of email templates available in salesforce.com?
1.        Text

2.        HTML with Letter Head

3.        Custom HTML

4.        Visual force
 
 
This time we will see, how to create email templates in Salesforce.com
Create Email Template in Salesforce
Create Email Template in Salesforce
To create email template, go to Personal Setup | Email | My Templates and click on New Template.

In type of Email template, we can select HTML, HTML with Letter Head , Visual force or without letter Head.
You can create four different types of email templates:
  • Text – All users can create or change text email templates. See Creating Text Email Templates.
  • HTML with letterhead – Administrators and users with the “Edit HTML Templates” permission can create HTML email templates based on a letterhead. See Creating HTML Email Templates.
  • Custom HTML – Administrators and users with the “Edit HTML Templates” permission can create custom HTML email templates without using a letterhead. You must either know HTML or obtain the HTML code to insert in your email template. See Creating Custom HTML Email Templates.
  • Visualforce – Administrators and developers can create templates using Visualforce. Visualforce email templates allow for advanced merging with a recipient’s data, where the content of a template can contain information from multiple records, see Creating Visualforce Email Templates.
All of these email templates can include text, merge fields, and attached files. You can also include images on your HTML and Visualforce templates. You can use email templates when you send an email from the Activity History related list of a record. Text and HTML templates can also be used when you send mass email. A button to check the spelling of your template is available for text templates andVisualforce templates without HTML tags.
Note : You cannot send a mass email using a Visualforce email template.
For Letter Head type, we first have to create the letterhead. So, Start with letterhead Creation:
Salesforce Letter Head Email template
Salesforce Letter Head Email template
After creating the Letterhead, I have created below Email Template:
Email Template in Salesforce with letter head
Email Template in Salesforce with letter head
As, you can see in above screen shot that Creating email template is very easy, you can use Object fields as a place holder.
In above email, Student name, Course , fees and Balance is Place holder which will be replaced on runtime.
To manage your personal email templates, click SetupEmailMy Templates. If you have permission to manage public email templates, click SetupCommunication TemplatesEmail Templates.
     1)Click on the name of any email template to go to the Viewing Email Templates page.
2)To edit or delete a template, click Edit or Del next to the template name in the list.
3)Click New Template to create any type of email template.
 
 
15. What are the different Salesforce.com Editions and Limits?
 
Salesforce Limits is a reference guide that covers a variety of limits associated with Salesforce features and products. However, Salesforce Limits doesn’t cover all limits and some limits may not apply to your organization. Keep in mind that stated limits aren’t a guarantee that the specified resource is available at its limit in all circumstances. For example, some limits depend on load, performance, and other system issues. In addition, Salesforce Limits doesn't include limits of:
     1)User interface elements in the Salesforce application
2)Field lengths of Salesforce objects
3)Desktop integration clients
All limits are subject to change at any time. Contact salesforce.com for more information.


16. What is Roll up summary field in Salesforce?

Roll up summary field in salesforce calculates the Count, Sum, Min or Max of particular field of any child record. Thus, we can say that Roll up summary field can only be created on Master object.

Note : Roll up summary field can only be defined on the master object.
While your formula fields calculate values using fields within a single record, roll-up summary fields calculate values from a set of related records, such as those in a related list. You can create roll-up summary fields that automatically display a value on a master record based on the values of records in a detail record. These detail records must be directly related to the master through a master-detail relationship.
refer this page, to study more about the roll up fields.
The Roll up Summary field is basically of 4 types:
  1. Count
  2. Sum
  3. Min
  4. Max

As, per our previous sessions on salesforce, lets create roll up field on object Course because this is the Master object.
I want to calculate total income from a course:
Go to App Setup | Create | Objects and click on New field and Select Roll up summary field.
In Step 2, enter the field name and help text etc.
For step 3, you will see below screen,
Salesforce Rollup Summary field
Salesforce Rollup Summary field
In above image, at 1 we have to select the child object, at 2 we have to select the field on which it should calculate.
In our case, Fees paid field is of Formula type which works on currency.
And in section 3 you ca specify weather this roll up summary field include all record or any specific record which comes under the criteria you specified.
So, after creation of Roll up field on Master object final look is shown below:
Salesforce Final look on Roll up summary field
Salesforce Final look on Roll up summary field





17. What will happen if the Account is deleted?

If the Account is deleted then Contact, Opportunity will also be deleted from Salesforce which are related to that Account.

From the database perspective, check below image of child relationships of Account:
























http://shivasoft.in/blog/wp-content/uploads/2010/09/Account-Child-relationship-in-salesforce.jpg
 
 

If we use schema builder, released in Winter 12 it would look like:
   
http://shivasoft.in/blog/wp-content/uploads/2010/09/Account-Contact-and-Opportunity-of-salesforce-in-schema-builder.png 
 

18. How many types of the relationship fields available in Salesforce?

Ans :

1.        Master Detail

2.        Many to Many

3.        Lookup

4.        Hierarchical (It is available only on User Object, we cannot create this relationship)
   
 
Use relationships to associate an object with other objects in Salesforce. For example, a relationship can link custom object records to standard object records in a related list, such as linking a custom object called “Bugs” to cases to track product defects associated with customer cases. You can define different types of relationships by creating custom relationship fields on an object. Before you begin creating relationships, determine the type of relationship that suits your needs.
There are different types of relationships between objects in Salesforce. Their differences include how they handle data deletion, sharing, and required fields in page layouts:
Master-detail
This type of relationship closely links objects together such that the master record controls certain behaviors of the detail and subdetail record. For example, you can define a two-object master-detail relationship, such as Account—Expense Report, that extends the relationship to subdetail records, such as Account—Expense Report—Expense Line Item. You can then perform operations across the master—detail—subdetail relationship.
Behaviors of master-detail relationships include:
  • Deleting a detail record moves it to the Recycle Bin and leaves the master record intact; deleting a master record also deletes related detail and subdetail records. Undeleting a detail record restores it, and undeleting a master record also undeletes related detail and subdetail records. However, if you delete a detail record and later, separately, delete its master record, you cannot undelete the detail record, as it no longer has a master record to relate to.
  • By default, records can’t be reparented in master-detail relationships. Administrators can, however, allow child records in master-detail relationships on custom objects to be reparented to different parent records by selecting the Allow reparenting option in the master-detail relationship definition.
  • The Owner field on the detail and subdetail records is not available and is automatically set to the owner of the master record. Custom objects on the “detail” side of a master-detail relationship can't have sharing rules, manual sharing, or queues, as these require the Owner field.
  • The security settings for the master record control the detail and subdetail records.
  • The master-detail relationship field (which is the field linking the objects) is required on the page layout of the detail and subdetail records.
  • The master object can be a standard object, such as Account or Opportunity, or a custom object.
  • As a best practice, don't exceed 10,000 child records for a master-detail relationship.
Many-to-many
You can use master-detail relationships to model many-to-many relationships between any two objects. A many-to-many relationship allows each record of one object to be linked to multiple records from another object and vice versa. For example, you may have a custom object called “Bug” that relates to the standard case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.
Lookup
This type of relationship links two objects together. Lookup relationships are similar to master-detail relationships, except they do not support sharing or roll-up summary fields. With a lookup relationship, you can:
  • Link two different objects.
  • Link an object with itself (with the exception of the user object; see Hierarchical). For example, you might want to link a custom object called “Bug” with itself to show how two different bugs are related to the same problem.
Note
Lookup relationships from objects related to the campaign member object aren’t supported; however, you can create lookup relationships from the campaign member object related to other objects.
When you create a lookup relationship, you can set these options:
  • Make the lookup field required for saving a record, requiring it on the corresponding page layout as well.
  • If the lookup field is optional, you can specify one of three behaviors to occur if the lookup record is deleted:
    • Clear the value of this field This is the default. Clearing the field is a good choice when the field does not have to contain a value from the associated lookup record.
    • Don’t allow deletion of the lookup record that’s part of a lookup relationship This option restricts the lookup record from being deleted if you have any dependencies, such as a workflow rule, built on the relationship.
    • Delete this record also Available only if a custom object contains the lookup relationship, not if it’s contained by a standard object. However, the lookup object can be either standard or custom. Choose when the lookup field and its associated record are tightly coupled and you want to completely delete related data. For example, say you have an expense report record with a lookup relationship to individual expense records. When you delete the report, you probably want to delete all of the expense records, too.
      Warning
      Choosing Delete this record also can result in a cascade-delete. A cascade-delete bypasses security and sharing settings, which means users can delete records when the target lookup record is deleted even if they don’t have access to the records. To prevent records from being accidentally deleted, cascade-delete is disabled by default. Contact Salesforce.com to get the cascade-delete option enabled for your organization.
      Cascade-delete and its related options are not available for lookup relationships to business hours, community, lead, price book, product, or user objects.
When you define a lookup relationship, you have the option to include a lookup field on the page layouts for that object as well as create a related list on the associated object's page layouts. For example, if you have a custom object called “PTO Requests” and you want your users to link a PTO request with the employee submitting the request, create a lookup relationship from the PTO Request custom object with the user object.
If the parent record in a lookup relationship is deleted, the field history tracking for the child record does not record the deletion. For example, if a parent account is deleted, the Account History related list for the child account does not show the deletion.
You can't delete an object or record in a lookup relationship if the combined number of records between the two linked objects is more than 100,000. To delete an object or record in a lookup relationship, first delete an appropriate number of its child records.
Hierarchical
This type of relationship is a special lookup relationship available only for the user object. It allows users to use a lookup field to associate one user with another that does not directly or indirectly refer to itself. For example, you can create a custom hierarchical relationship field to store each user's direct manager.
Tip
When creating a hierarchical field in Personal, Contact Manager, Group, and Professional Editions, you can select the Restricted Field checkbox so that only users with the “Manage Users” permission can edit it. In Enterprise, Unlimited, and Developer Edition, use field-level security instead.
 

19. How to create many to many relationships between object?

Creating many to many relationship in salesforce is little tricky. You cannot create this type of relationship directly. Follow below steps to create this type of relationship.

Create both objects which should be interlinked.

Create one custom object (also called as junction object), which should have autonumber as unique identification and create two master relationships for both objects, no need create tab for this object.

Now on both object, add this field as related list.
  In Interview for the salesforce technology, one common question asked is how to implement the many to many relationship. If we answer that using junction object then there next question comes how ? explain it and after that, next question will be what happen if i delete one master record ?
So, in this article i will first show you that how to create custom objects, how to relate them and what will happen if we delete master or child?
here i am going to assume that we want to relate A and B. Let us assume that we have two custom object - A and B.
To provide the many to many relationship between A and B, we will need to create one more object let’s say it would be C, it will be called as junction object.
So, start with creating Object A.
Creating Custom object in salesforce
Creating Custom object in salesforce
In same way, as shown in above image create B and C. For the simplicity of the example i have not added any field in Object A and B. By default Name field is provided by the salesforce on all objects.
We are going to use the object C as a junction object for A and B.
on object C, create “first Master-Detail” field and select object A as parent. This will be Primary Master – Detail relationship.
Salesforce Master-Detail relationship - select Master object
Salesforce Master-Detail relationship - select Master object
In next screen give the name of the field.
Salesforce Master-Detail relationship - Give the field Name
Salesforce Master-Detail relationship - Give the field Name
for the Master record A, i have used name “ChildOfA” and in same way for the Master record B – i used “ChildOfB”.
Untill now, we have created two fields on object C in which one refer to master record A and other will refer master record B as shown in below screen. Now we can create a tab for all the custom objects to add the record. First create record for A then B and for record C screen will look like below snap.
Salesforce Master-Detail relationship - Many to Many Relationship
Salesforce Master-Detail relationship - Many to Many Relationship
Few important points (Interview Questions of salesforce ):
  1. One Object can have only two Master-Detail relationships.
  2. If we delete record A (First Master detail relationship is always primary)  – then child record c will be deleted.
  3. If we delete record B then in this case also child record C will be deleted.
  4. If we delete record c then only C will be deleted , master record will not be deleted.
If child C has two Master record A and B, Where A is primary relation then Child record C will inherit the look and feel of Parent object A
 
To create a many-to-many relationship: “Customize Application”
You can use master-detail relationships to model many-to-many relationships between any two objects. A many-to-many relationship allows each record of one object to be linked to multiple records from another object and vice versa. For example, you may have a custom object called “Bug” that relates to the standard case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs. When modeling a many-to-many relationship, you use a junction object to connect the two objects you want to relate to each other.
Junction Object
A custom object with two master-detail relationships. Using a custom junction object, you can model a “many-to-many” relationship between two objects. For example, you may have a custom object called “Bug” that relates to the standard case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.
Creating the many-to-many relationship consists of:
  1. Creating the junction object.
  2. Creating the two master-detail relationships.
  3. Customizing the related lists on the page layouts of the two master objects.
  4. Customizing reports to maximize the effectiveness of the many-to-many relationship.

Creating the Junction Object

To create the junction object:
  1. From Setup, click Create | Objects.
  2. Click New Custom Object.
  3. In the custom object wizard, consider these tips specifically for junction objects:
    • Name the object with a label that indicates its purpose, such as BugCaseAssociation.
    • For the Record Name field, it is recommended that you use the auto-number data type.
    • Do not launch the custom tab wizard before clicking Save. Junction objects do not need a tab.

Creating the Two Master-Detail Relationships

To create the two master-detail relationships:
  1. Verify that the two objects you want to relate to each other already exist. For example, you may want to relate the standard case object to a custom bug object.
  2. On the junction object, create the first master-detail relationship field. In the custom field wizard:
    1. Choose Master-Detail Relationship as the field type.
    2. Select one of the objects to relate to your junction object. For example, select Case.
      The first master-detail relationship you create on your junction object becomes the primary relationship. This affects the following for the junction object records:
      • Look and feel: The junction object's detail and edit pages use the color and any associated icon of the primary master object.
      • Record ownership: The junction object records inherit the value of the Owner field from their associated primary master record. Because objects on the detail side of a relationship do not have a visible Owner field, this is only relevant if you later delete both master-detail relationships on your junction object.
      • Division: If your organization uses divisions to segment data, the junction object records inherit their division from their associated primary master record. Similar to the record ownership, this is only relevant if you later delete both master-detail relationships.
    3. Select a Sharing Setting option. For master-detail relationship fields, the Sharing Setting attribute determines the sharing access that users must have to a master record in order to create, edit, or delete its associated detail records.
    4. For the Related List Label that will display on the page layout of the master object, do not accept the default. Change this to use the name of the other master object in your many-to-many relationship. For example, change this to Bugs so users will see a Bugs related list on the case detail page.
  3. On the junction object, create the second master-detail relationship. In the custom field wizard:
    1. Choose Master-Detail Relationship as the field type.
    2. Select the other desired master object to relate to your junction object. For example, select Bug.
      The second master-detail relationship you create on your junction object becomes the secondary relationship. If you delete the primary master-detail relationship or convert it to a lookup relationship, the secondary master object becomes primary.
    3. Select a Sharing Setting option. For master-detail relationship fields, the Sharing Setting attribute determines the sharing access that users must have to a master record in order to create, edit, or delete its associated detail records.
    4. For the Related List Label that will display on the page layout of the master object, do not accept the default. Change this to use the name of the other master object in your many-to-many relationship. For example, change this to Cases so users will see a Cases related list on the bug detail page.

Customizing Many-to-Many Relationship Related Lists

For a many-to-many relationship in Salesforce, each master object record displays a related list of the associated junction object records. To create a seamless user experience, you can change the name of the junction object related list on each of the master object page layouts to have the name of the other master object. For example, you might change the BugCaseAssociations related list to Cases on the bugs page layout and to Bugs on the cases page layout. You can further customize these related lists to display fields from the other master object.
To customize the fields that display in the junction object related list on each master object page layout:
  1. Edit the page layout of each master object that is related to the junction object. For example, to modify the BugCaseAssociations related list for case records, edit the page layout for cases from Setup by clicking Customize | Cases | Page Layouts.
  2. Edit the properties of the related list you want to modify. For example, on cases the BugCaseAssociations related list was renamed to Bugs, so select the Bugs related list.
  3. Add the fields to display in the related list. You can add fields from the junction object itself, but more importantly, you can add fields from the other master object.
    Each field is prefixed with its object name in the popup window. In the related list itself, only fields from the junction object are prefixed with the object name; fields from the other master object are not.
Note
The junction object related list does not include an icon on the master record's detail pages because the junction object does not have a custom tab. If you make a tab for the junction object, the icon is included.

Customizing Reports for Many-to-Many Relationships

Many-to-many relationships provide two standard report types that join the master objects and the junction object. The report types are:
  • “Primary master with junction object and secondary master” in the primary master object's report category.
  • “Secondary master with junction object and primary master” in the secondary master object's report category.
The order of the master objects in the report type is important. The master object listed first determines the scope of records that can be displayed in the report.
You can create custom reports based on these standard report types. In addition, you can create custom report types to customize which related objects are joined in the report.
See Also:

23. How to delete the users data from Salesforce?

Ans : To delete the Users Data go to Setup | Administration Setup | Data Management |  Mass Delete Record, from there select the objects like Account, Lead etc and in criteria select the users name and delete all records of that user related to particular object.




24. How to restrict the user to see any record, lets say opportunity?

Ans : set up opportunity sharing to be private.  If both users are admins or have view all records on opportunity, then that overrides private sharing.




25. What is the difference between trigger.new and trigger.old in Apex – SFDC?

Ans :

Trigger.new :

Returns a list of the new versions of the sObject records.

Note that this sObject list is only available in

insert and

update triggers, and the records can only be modified in

beforetriggers.

Trigger.old :

Returns a list of the old versions of the sObject records.

Note that this sObject list is only available in

update and

delete triggers.




26. How to restrict any Trigger to fire only once ?

Ans:

Triggers can fire twice, once before workflows and once after workflows, this is documented at
 
 

Triggers and Order of Execution

When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order.
Note
Before Salesforce executes these events on the server, the browser runs JavaScript validation if the record contains any dependent picklist fields. The validation limits each dependent picklist field to its available values. No other validation occurs on the client side.
On the server, Salesforce:
  1. Loads the original record from the database or initializes the record for an upsert statement.
  2. Loads the new record field values from the request and overwrites the old values.
    If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
    • Compliance with layout-specific rules
    • Required values at the layout level and field-definition level
    • Valid field formats
    • Maximum field length
    Salesforce doesn't perform system validation in this step when the request comes from other sources, such as an Apex application or a SOAP API call.
  3. Executes all before triggers.
  4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn't run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
  5. Saves the record to the database, but doesn't commit yet.
  6. Executes all after triggers.
  7. Executes assignment rules.
  8. Executes auto-response rules.
  9. Executes workflow rules.
  10. If there are workflow field updates, updates the record again.
  11. If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.
    Note
    The before and after triggers fire one more time only if something needs to be updated. If the fields have already been set to a value, the triggers are not fired again.
  12. Executes escalation rules.
  13. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  14. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.
  15. Executes Criteria Based Sharing evaluation.
  16. Commits all DML operations to the database.
  17. Executes post-commit logic, such as sending email.
Note
During a recursive save, Salesforce skips steps 7 through 14.

Additional Considerations

Please note the following when working with triggers.
  • The order of execution isn’t guaranteed when having multiple triggers for the same object due to the same event. For example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the order in which these triggers fire isn’t guaranteed.
  • When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity is created, before the opportunity contact role is created. For more information, see “Customizing Lead Settings” in the Salesforce online help.
  • If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as follows:
    • If you set Stage and Forecast Category, the opportunity record contains those exact values.
    • If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults to the one associated with trigger Stage.
    • If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category value should also come from the API call or user interface. If no value for Forecast Category is specified and the incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted.
  • If you are cloning an opportunity with products, the following events occur in order:
    1. The parent opportunity is saved according to the list of events shown above.
    2. The opportunity products are saved according to the list of events shown above.
    Note
    If errors occur on an opportunity product, you must return to the opportunity and fix the errors before cloning.
    If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity.
  • Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last update trigger won’t contain the version of the object immediately prior to the workflow update, but the object before the initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than 10, as would typically be the case.
&amp;#160; 
 
 
 
 
“The before and after triggers fire one more time only if something needs to be updated. If the fields have already been set to a value, the triggers are not fired again.”

Workaround:

Add a static boolean variable to a class, and check its value within the affected triggers.


1

public class HelperClass {

2

   public static boolean firstRun = true;



3

}

4

trigger affectedTrigger on Account (before delete, after delete, after undelete) {



5

    if(Trigger.isBefore){

6

        if(Trigger.isDelete){



7

            if(HelperClass.firstRun){

8

                Trigger.old[0].addError('Before Account Delete Error');



9

                HelperClass.firstRun=false;

10

            }







11

        }

12

    }



13

}




27.  What is difference between WhoId and WhatId in the Data Model of Task ?

Ans :

WhoID refers to people things. So that would be typically a Lead ID or a Contact ID
WhatID refers to object type things. That would typically be an Account ID or an Opportunity ID
 
ERD for task and event objects 
 
 
 

28. Where is the option of the report for the “Custom Object with related object” and what are the condition to generate related reports?
Ans :

If the parent object is the standard object provided by the salesforce like “Account”, “Contact” then the report will be in there section with related custom object.
If both objects are the custom then the report will be in “
Other Reports” Sections.

Following are the conditions to get the report of related objects:

·         On both the objects, Reports option must be enable.

·         The relationship between both of them must be “Master – detail relationship”.
 
Very often  it is observed that after creating the custom object which is related to other object, developers get surprise that where is the report option for my object with that custom object.
When creating a custom object, you can use the “Relationships” section to define relationships between this new object and other objects. For example let’s say you have a new object called “Expense” that you want to attach to an “Account“.
When you check the “enable reports” box and you go to the report wizard where you choose the type of data you want to report on,  after the standard sections like “Accounts & Contacts”,  ”Opportunities”,  ”Administrative Reports”  you’ll see a new section for “Other Reports”. When you choose that section you’ll see an “Expenses” report type only.
However, if you want to see a report linking “Expenses with Accounts” see below:
  1. Ensure that the relationship between accounts and expenses is a master-detail relationship.
  2. Look for the “Accounts with Expenses” report in the Accounts & Contacts section, not the “Other Reports” section because Account is the Parent object.
Lets take the example of our previously created application of the “Student and Courses“, in which course is the parent object.
As the parent object is not the standard object, in this case the report will be in the “Other reports” section as shown in below image.
Report of custom object with related object in Salesforce
Report of custom object with related object in Salesforce
Hi hope, this article will help to find the cause and solution that where is the custom objects report in salesforce.