• thangasan@yahoo
  • NEWBIE
  • 144 Points
  • Member since 2007

  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 29
    Replies

Hello,


I want to write a Visualforce page, and write out the data explicitly rather than use <apex:detail />.

 

The problem I'm having is I can't seem to find an example of defining # columns to print out the data.

 

In the Pages Developer Guide, I see examples of <apex:pageBlockTable>, which just loops printing data form a related list;  I see an example of <apex:dataTable>, but don't see how to setup the # of columns.

 

Can someone tell me out to get started.  For example, if I wanted to print out Contact details similar to how <apex:detail /> woudl output it, can you give me the first few lines of the Visualforce code?

 

Thanks,


AT

 

 

I have the following code in one of the controller extension methods:

 

confirm() { 

PageReference p = Page.offbsubmit;

p.setRedirect(true);

return p;

}

 

I am testing the above code in testMethod using the following statement..

 

PageReference q = test.confirm();

PageReference s = Page.offbsubmit;

system.assertEquals(q, s); // getting an exception here!!

 

I am getting the following exception:

 

System.Exception: Assertion Failed: Expected: System.PageReference[/apex/offbsubmit], Actual: System.PageReference[/apex/offbsubmit] 

 

which doesnt make anysense to me because the expected and the actual values are the same..any help?

 

Message Edited by mallikam on 07-28-2009 11:10 AM

I am new to Email Services and Apex and wanting to learn effective methods for testing classes that implement the Messaging.InboundEmailHandler.  Please refer me to any good material for learning test methods and best practices for conducting them.  Please see the class code (ProcessApplicant) and Initial Test method Apex Class.  I'm only getting 16% code coverage using the current test method.

 

Thanks,

SCR

/* * This class implements Message.InboundEmailHandler to accept inbound applications for a given position. * It results in a new Candidate (if one doesnt already exist) and Job Description record being created. * Any binary email attachments are automatically transfered to the Job Description as attachments on the Notes and Attachments related list. */ global class ProcessApplicant implements Messaging.InboundEmailHandler { private static final String PHONE_MATCH = 'Phone:'; global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope) { // Indicates if the message processes successfully, permits an error response to be sent back to the user. Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try { // Obtain the applicants name and the position they are applying for from the email. String firstName = email.fromname.substring(0,email.fromName.indexOf(' ')); String lastName = email.fromname.substring(email.fromName.indexOf(' ')); String positionName = email.subject; String emailBody = email.plainTextBody; String emailFrom = envelope.fromAddress; // Process the email information. processApplicantEmail(firstName, lastName, positionName, emailBody, emailFrom, email.binaryAttachments); // Success. result.success = true; } catch (Exception e) { // Return an email message to the user. result.success = false; result.message = 'An error occured processing your message. ' + e.getMessage(); } return result; } public static void processApplicantEmail(String firstName, String lastName, String positionName, String emailBody, String emailFrom, Messaging.InboundEmail.BinaryAttachment[] binaryAttachments) { // Obtain the applicants Phone number from the message body. integer phoneMatchIdx = emailBody.indexOf(PHONE_MATCH); if(phoneMatchIdx==-1) throw new ProcessApplicantException('Please state your phone number following Phone: in your message.'); String phoneNumber = emailBody.substring(phoneMatchIdx+PHONE_MATCH.length()); // Resolve the Id of the Position they are applying for. Id positionId; try { // Lookup the Position they are applying for by name. Position__c position = [select Id from Position__c where name = :positionName limit 1]; positionId = position.Id; } catch (Exception e) { // Record not found. throw new ProcessApplicantException('Sorry the position ' + positionName + ' does not currently exist.'); } // Candidate record for the applicant sending this email. Candidate__c candidate; try { // Attempt to read an existing Candidate by email address. Candidate__c[] candidates = [select Id from Candidate__c where email__c = :emailFrom]; candidate = candidates[0]; } catch (Exception e) { // Record not found, create a new Candidate record for this applicant. candidate = new Candidate__c(); candidate.email__c = emailFrom; candidate.first_name__c = firstName; candidate.last_name__c = lastName; candidate.phone__c = phoneNumber; insert candidate; } // Create the Job Application record. Job_Application__c jobApplication = new Job_Application__c(); jobApplication.Position__c = positionId; jobApplication.Candidate__c = candidate.id; insert jobApplication; // Store any email attachments and associate them with the Job Application record. if (binaryAttachments!=null && binaryAttachments.size() > 0) { for (integer i = 0 ; i < binaryAttachments.size() ; i++) { Attachment attachment = new Attachment(); attachment.ParentId = jobApplication.Id; attachment.Name = binaryAttachments[i].Filename; attachment.Body = binaryAttachments[i].Body; insert attachment; } } // Confirm receipt of the applicants email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses( new String[] { emailFrom }); mail.setSubject('Your job application has been received'); mail.setPlainTextBody('Thank you for submitting your resume. Your application will be reviewed to determine if an interview will be scheduled.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } /* * Represents errors that have occured interpretting the incoming email message */ class ProcessApplicantException extends Exception { } }

 

 

//The ProcessApplicant Test: public class ProcessApplicantTest { public static testMethod void ProcessApplicantTest(){ System.debug('Im starting a method'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); email.subject = 'test'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); catcher.handleInboundEmail(email, envelope); } }

 

  • July 21, 2009
  • Like
  • 0

Hai

 

    In Site lookup Screen not having filter why ?,But when i saw normal salesforce lookup Screen having

ShowFilter option.

 

   Note: Search Setting Enhanced Lookups enabled for Particular Object

 

 

Thanks and Regards

Thangaraj S

 

Hai
  I have one Component which contains dataTable in outputPanel and button,
The dataTable have Some input Text Field,
After enter some value in input Text field and click the button in Component ,
it rerender the outputPanel and need to display dataTable with outPutText with entered value ( Similarly like
Confirmation page) ,When we run that page which contain component  in Site,
After clicking the button  the dataTable disappears .
Any Idea why dataTable disappeared ?
dataTable inside contains both inputText and outputText based on button click its rendered both inputText and outputText display also one Component.
Thanks
Thanga
 

Hai

 

  I am trying Bulk API Enterprise WSD in SandBox the below error is coming

 

 Exception in thread "main" [AsyncApiException  exceptionCode='ClientInputError'
 exceptionMessage='Failed to create job '
]

 at com.sforce.async.RestConnection.createOrUpdateJob(RestConnection.java:102)
 at com.sforce.async.RestConnection.createJob(RestConnection.java:76)
 at client.BulkClient.createJob(BulkClient.java:162)
 at client.BulkClient.runSample(BulkClient.java:56)
 at client.BulkClient.main(BulkClient.java:45)
Caused by: java.net.NoRouteToHostException: No route to host: connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)
 at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
 at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
 at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
 at java.net.Socket.connect(Socket.java:519)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
 at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
 at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
 at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:271)
 at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
 at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:816)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
 at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:881)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
 at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:132)
 at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:63)
 at com.sforce.async.RestConnection.createOrUpdateJob(RestConnection.java:82)
 ... 4 more

 

Source

 

package client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.rpc.ServiceException;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BatchInfo;
import com.sforce.async.BatchStateEnum;
import com.sforce.async.CSVReader;
import com.sforce.async.ContentType;
import com.sforce.async.JobInfo;
import com.sforce.async.JobStateEnum;
import com.sforce.async.OperationEnum;
import com.sforce.async.RestConnection;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class BulkClient {
 private LoginResult loginResult;

 /**
  * @param args
  */
 public static void main(String[] args) throws ServiceException,AsyncApiException,
   ConnectionException, IOException {
  BulkClient bc = new BulkClient();
  bc.runSample("Account", "userID", "password", "Sample.csv");
 }

 /**
  * Creates a Bulk API. job and uploads batches for a CSV file.
  */
 public void runSample(String sobjectType, String userName, String password,
   String sampleFileName) throws ServiceException,AsyncApiException,
   ConnectionException, IOException {
  login(userName, password);
  RestConnection connection = getRestConnection();
  JobInfo job = createJob(sobjectType, connection);
  List<BatchInfo> batchInfoList = createBatchesFromCSVFile(connection,
    job, sampleFileName);
  closeJob(connection, job.getId());
  awaitCompletion(connection, job, batchInfoList);
  checkResults(connection, job, batchInfoList);
 }

 private boolean login(String userName, String password) throws ServiceException {
  SoapBindingStub binding = (SoapBindingStub) new SforceServiceLocator().getSoap();

  // Time out after a minute
  binding.setTimeout(60000);
  System.getProperties().put("proxySet", "true");
  System.getProperties().put("http.proxyHost", "proxy");
  System.getProperties().put("http.proxyPort", "8080");

  try {
   System.out.println("LOGGING IN NOW....");
   loginResult = binding.login(userName, password);
  } catch (LoginFault ex) {
   // The LoginFault derives from AxisFault
   ExceptionCode exCode = ex.getExceptionCode();
   if (exCode == ExceptionCode.FUNCTIONALITY_NOT_ENABLED
     || exCode == ExceptionCode.INVALID_CLIENT
     || exCode == ExceptionCode.INVALID_LOGIN
     || exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_DOMAIN
     || exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_TIME
     || exCode == ExceptionCode.ORG_LOCKED
     || exCode == ExceptionCode.PASSWORD_LOCKOUT
     || exCode == ExceptionCode.SERVER_UNAVAILABLE
     || exCode == ExceptionCode.TRIAL_EXPIRED
     || exCode == ExceptionCode.UNSUPPORTED_CLIENT) {
    System.out
      .println("Please be sure that you have a valid username "
        + "and password.");
   } else {
    // Write the fault code to the console
    System.out.println(ex.getExceptionCode());
    // Write the fault message to the console
    System.out.println("An unexpected error has occurred."
      + ex.getMessage());
   }
   return false;
  } catch (Exception ex) {
   System.out.println("An unexpected error has occurred: "
     + ex.getMessage());
   ex.printStackTrace();
   return false;
  }
  // Check if the password has expired
  if (loginResult.isPasswordExpired()) {
   System.out
     .println("An error has occurred. Your password has expired.");
   return false;
  }
  binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,
    loginResult.getServerUrl());
  System.out.println(loginResult.getServerUrl());
  SessionHeader sh = new SessionHeader();
  sh.setSessionId(loginResult.getSessionId());
  binding.setHeader(new SforceServiceLocator().getServiceName()
    .getNamespaceURI(), "SessionHeader", sh);
  return true;
 }

 /**
  * Create the RestConnection used to call Bulk API operations.
  */
 private RestConnection getRestConnection()
   throws ConnectionException, AsyncApiException {

  ConnectorConfig config = new ConnectorConfig();
  config.setSessionId(loginResult.getSessionId());
  String soapEndpoint = loginResult.getServerUrl();
  String apiVersion = "17.0";
  String restEndpoint = soapEndpoint.substring(0, soapEndpoint
    .indexOf("Soap/"))
    + "async/" + apiVersion;
  System.out.println(restEndpoint);
  config.setRestEndpoint(restEndpoint);
  config.setCompression(true);
  config.setTraceMessage(false);
  RestConnection connection = new RestConnection(config);
  return connection;
 }

 /**
  * Create a new job using the Bulk API.
  **
  * @param sobjectType
  *            The object type being loaded, such as "Account"
  * @param connection
  *            RestConnection used to create the new job.
  * @return The JobInfo for the new job.
  * @throws AsyncApiException
  */
 private JobInfo createJob(String sobjectType, RestConnection connection)
   throws AsyncApiException {
  JobInfo job = new JobInfo();
  job.setObject(sobjectType);
  job.setOperation(OperationEnum.insert);
  job.setContentType(ContentType.CSV);
//  System.getProperties().put("proxySet", "true");
//  System.getProperties().put("http.proxyHost", "proxy");
//  System.getProperties().put("http.proxyPort", "8080");
  job = connection.createJob(job);
  System.out.println(job);
  return job;
 }

 private List<BatchInfo> createBatchesFromCSVFile(RestConnection connection,
   JobInfo jobInfo, String csvFileName) throws IOException,
   AsyncApiException {
  List<BatchInfo> batchInfos = new ArrayList<BatchInfo>();
  BufferedReader rdr = new BufferedReader(new InputStreamReader(
    new FileInputStream(csvFileName)));
  // read the CSV header row
  byte[] headerBytes = (rdr.readLine() + "\n").getBytes("UTF-8");
  int headerBytesLength = headerBytes.length;
  File tmpFile = File.createTempFile("bulkAPIInsert", ".csv");
  // Split the CSV file into multiple batches
  try {
   FileOutputStream tmpOut = new FileOutputStream(tmpFile);
   int maxBytesPerBatch = 10000000; // 10 million bytes per batch
   int maxRowsPerBatch = 10000; // 10 thousand rows per batch
   int currentBytes = 0;
   int currentLines = 0;
   String nextLine;
   while ((nextLine = rdr.readLine()) != null) {
    byte[] bytes = (nextLine + "\n").getBytes("UTF-8");
    // Create a new batch when our batch size limit is reached
    if (currentBytes + bytes.length > maxBytesPerBatch
      || currentLines > maxRowsPerBatch) {
     createBatch(tmpOut, tmpFile, batchInfos, connection,
       jobInfo);
     currentBytes = 0;
     currentLines = 0;
    }
    if (currentBytes == 0) {
     tmpOut = new FileOutputStream(tmpFile);
     tmpOut.write(headerBytes);
     currentBytes = headerBytesLength;
     currentLines = 1;
    }
    tmpOut.write(bytes);
    currentBytes += bytes.length;
    currentLines++;
   }
   // Finished processing all rows
   // Create a final batch for any remaining data
   if (currentLines > 1) {
    createBatch(tmpOut, tmpFile, batchInfos, connection, jobInfo);
   }
  } finally {
   tmpFile.delete();
  }
  return batchInfos;
 }

 private void createBatch(FileOutputStream tmpOut, File tmpFile,
   List<BatchInfo> batchInfos, RestConnection connection,
   JobInfo jobInfo) throws IOException, AsyncApiException {
  tmpOut.flush();
  tmpOut.close();
  FileInputStream tmpInputStream = new FileInputStream(tmpFile);
  try {
   BatchInfo batchInfo = connection.createBatchFromStream(jobInfo,
     tmpInputStream);
   System.out.println(batchInfo);
   batchInfos.add(batchInfo);
  } finally {
   tmpInputStream.close();
  }
 }

 private void closeJob(RestConnection connection, String jobId)
   throws AsyncApiException {
  JobInfo job = new JobInfo();
  job.setId(jobId);
  job.setState(JobStateEnum.Closed);
  connection.updateJob(job);
 }

 private void awaitCompletion(RestConnection connection, JobInfo job,
   List<BatchInfo> batchInfoList) throws AsyncApiException {
  long sleepTime = 0L;
  Set<String> incomplete = new HashSet<String>();
  for (BatchInfo bi : batchInfoList) {
   incomplete.add(bi.getId());
  }
  while (!incomplete.isEmpty()) {
   try {
    Thread.sleep(sleepTime);
   } catch (InterruptedException e) {
   }
   System.out.println("Awaiting results..." + incomplete.size());
   sleepTime = 10000L;
   BatchInfo[] statusList = connection.getBatchInfoList(job.getId())
     .getBatchInfo();
   for (BatchInfo b : statusList) {
    if (b.getState() == BatchStateEnum.Completed
      || b.getState() == BatchStateEnum.Failed) {
     if (incomplete.remove(b.getId())) {
      System.out.println("BATCH STATUS:\n" + b);
     }
    }
   }
  }
 }

 private void checkResults(RestConnection connection, JobInfo job,
   List<BatchInfo> batchInfoList) throws AsyncApiException,
   IOException {
  // batchInfoList was populated when batches were created and submitted
  for (BatchInfo b : batchInfoList) {
   CSVReader rdr = new CSVReader(connection.getBatchResultStream(job
     .getId(), b.getId()));
   List<String> resultHeader = rdr.nextRecord();
   int resultCols = resultHeader.size();
   List<String> row;
   while ((row = rdr.nextRecord()) != null) {
    Map<String, String> resultInfo = new HashMap<String, String>();
    for (int i = 0; i < resultCols; i++) {
     resultInfo.put(resultHeader.get(i), row.get(i));
    }
    boolean success = Boolean.valueOf(resultInfo.get("Success"));
    boolean created = Boolean.valueOf(resultInfo.get("Created"));
    String id = resultInfo.get("Id");
    String error = resultInfo.get("Error");
    if (success && created) {
     System.out.println("Created row with id " + id);
    } else if (!success) {
     System.out.println("Failed with error: " + error);
    }
   }
  }
 }

}

In the above Source code Login is OK, after that creating Job with Restful connection error occured

Bulk API need to set Proxy ?? ,Because i am running this application in Proxy network.

 

 

 

Please Help

 

Thanks and Regards

Thanga

Message Edited by thangasan@yahoo on 10-18-2009 11:24 PM

Hi

 

 Custom Setting List ,Name field if we enter more then 5 Double byte char then it gives error
Sample data
  関根 秀治

 

 Is there any restriction in Name field ? For Single bytes its accepting 38 Char.

 

 It seems 1 double bytes its calculating 9 char .So we can enter 4 Double bytes and 2 Char like this.

 

 

An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience.

Thank you again for your patience and assistance. And thanks for using salesforce.com!

Error ID: 1700040002-861 (91623632)

 

 

Thanks and Regards

Thanga

Hai

 

  Any one confirm Custom Setting Data can be insert by Apex DML Operation ?

  Because i am getting the below Error during Insert.( Using Apex Batch I am inserting ).

 

System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: 1512696965-168 (489760386): []

Thanks and Regards

Thangaraj S

 

Hai

 

During Approval Process ,The actual approver approved the record

that time field update is called in custom object.

In the custom object Trigger when i saw After and Before update Trigger

the LastModifiedById is different .

Any idea why its different ?

 

ie Before Update Trigger LastModifiedById is Creater id ( Creater is Submitter)

    After Trigger LastModifiedById is Approver Id

 

My Doubts is Inside Trigger What value is coming only update into table ?

 

Thanks and Regards

Thanga

 

Hai

 

I have written trigger for sending Email
when i use setHtmlBody with Japanese Character the Email having Junk Character
Any one have this problem ? Any Idea to solve this ?

 

Thanks

Thanga 

 

Hi
 
  For Creating Custom Object programmatic using Metadata API I am receive the following Error Can any one help
 
AxisFault
 faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Client
 faultSubcode:
 faultString: Must specify a {http://www.w3.org/2001/XMLSchema-instance}type attribute value for the {http://soap.sforce.com/2006/04/metadata}metadata element
 faultActor:
 faultNode:
 faultDetail:
 {http://xml.apache.org/axis/}stackTrace:Must specify a {http://www.w3.org/2001/XMLSchema-instance}type attribute value for the {http://soap.sforce.com/2006/04/metadata}metadata element
 
here is the code
 
Code:
MetadataBindingStub stub = (MetadataBindingStub) new MetadataServiceLocator().getMetadata();
stub.setTimeout(60000);

// Login using Partner WSDL 
// Getting the Session ID from Partner WSDL


SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());

stub.setHeader(new MetadataServiceLocator().getServiceName()
  .getNamespaceURI(), "SessionHeader", sh);


CustomObject co = new CustomObject();
String name = "MyNewObj";
co.setFullName(name + "__c");
co.setDeploymentStatus(DeploymentStatus.Deployed);
co.setDescription("Created by the Metadata API");
co.setEnableActivities(true);
co.setLabel(name + " Object");
co.setPluralLabel(co.getLabel() + "s");
co.setSharingModel(SharingModel.ReadWrite);
CustomField nf = new CustomField();
nf.setType(FieldType.Text);
nf.setLabel(co.getFullName() + " Name");
co.setNameField(nf);
AsyncResult[] ars = stub.create(new Metadata[] { co} );

 
Note SessionHeader Class also Import from partner WSDL .
Metadata.wsdl not generating SessionHeader.java.
 
Thanks
Thanga
 
Hai
 
  I am creating binding Object Using Session ID and Server URL in my server side. From my server i am inserting data into custom object using binding.create() method(Record is Inserting).I already created Approval Process for my custom Object in SF engin. So for Initial Submit of the inserted Record
i am using binding.process() method ,That time i am received
   "UNSUPPORTED_API_VERSION: This call requires a minimum API version of 8.0. Please upgrade to the latest version of the WSDL."
Error.
  Same Logic is working with creating binding Object with UserID and Password. I can`t store UserID and Password in My Server Side , So I am getting SessionID and Server URL and creating Binding Object.

  I am using Both case enterprise.wsdl ver 10.0
  Please help how to solve this problem.
 
Thanga
 
 

Hai

 

  I am trying Bulk API Enterprise WSD in SandBox the below error is coming

 

 Exception in thread "main" [AsyncApiException  exceptionCode='ClientInputError'
 exceptionMessage='Failed to create job '
]

 at com.sforce.async.RestConnection.createOrUpdateJob(RestConnection.java:102)
 at com.sforce.async.RestConnection.createJob(RestConnection.java:76)
 at client.BulkClient.createJob(BulkClient.java:162)
 at client.BulkClient.runSample(BulkClient.java:56)
 at client.BulkClient.main(BulkClient.java:45)
Caused by: java.net.NoRouteToHostException: No route to host: connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)
 at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
 at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
 at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
 at java.net.Socket.connect(Socket.java:519)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
 at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
 at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
 at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:271)
 at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
 at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:816)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
 at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:881)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
 at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:132)
 at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:63)
 at com.sforce.async.RestConnection.createOrUpdateJob(RestConnection.java:82)
 ... 4 more

 

Source

 

package client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.rpc.ServiceException;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BatchInfo;
import com.sforce.async.BatchStateEnum;
import com.sforce.async.CSVReader;
import com.sforce.async.ContentType;
import com.sforce.async.JobInfo;
import com.sforce.async.JobStateEnum;
import com.sforce.async.OperationEnum;
import com.sforce.async.RestConnection;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class BulkClient {
 private LoginResult loginResult;

 /**
  * @param args
  */
 public static void main(String[] args) throws ServiceException,AsyncApiException,
   ConnectionException, IOException {
  BulkClient bc = new BulkClient();
  bc.runSample("Account", "userID", "password", "Sample.csv");
 }

 /**
  * Creates a Bulk API. job and uploads batches for a CSV file.
  */
 public void runSample(String sobjectType, String userName, String password,
   String sampleFileName) throws ServiceException,AsyncApiException,
   ConnectionException, IOException {
  login(userName, password);
  RestConnection connection = getRestConnection();
  JobInfo job = createJob(sobjectType, connection);
  List<BatchInfo> batchInfoList = createBatchesFromCSVFile(connection,
    job, sampleFileName);
  closeJob(connection, job.getId());
  awaitCompletion(connection, job, batchInfoList);
  checkResults(connection, job, batchInfoList);
 }

 private boolean login(String userName, String password) throws ServiceException {
  SoapBindingStub binding = (SoapBindingStub) new SforceServiceLocator().getSoap();

  // Time out after a minute
  binding.setTimeout(60000);
  System.getProperties().put("proxySet", "true");
  System.getProperties().put("http.proxyHost", "proxy");
  System.getProperties().put("http.proxyPort", "8080");

  try {
   System.out.println("LOGGING IN NOW....");
   loginResult = binding.login(userName, password);
  } catch (LoginFault ex) {
   // The LoginFault derives from AxisFault
   ExceptionCode exCode = ex.getExceptionCode();
   if (exCode == ExceptionCode.FUNCTIONALITY_NOT_ENABLED
     || exCode == ExceptionCode.INVALID_CLIENT
     || exCode == ExceptionCode.INVALID_LOGIN
     || exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_DOMAIN
     || exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_TIME
     || exCode == ExceptionCode.ORG_LOCKED
     || exCode == ExceptionCode.PASSWORD_LOCKOUT
     || exCode == ExceptionCode.SERVER_UNAVAILABLE
     || exCode == ExceptionCode.TRIAL_EXPIRED
     || exCode == ExceptionCode.UNSUPPORTED_CLIENT) {
    System.out
      .println("Please be sure that you have a valid username "
        + "and password.");
   } else {
    // Write the fault code to the console
    System.out.println(ex.getExceptionCode());
    // Write the fault message to the console
    System.out.println("An unexpected error has occurred."
      + ex.getMessage());
   }
   return false;
  } catch (Exception ex) {
   System.out.println("An unexpected error has occurred: "
     + ex.getMessage());
   ex.printStackTrace();
   return false;
  }
  // Check if the password has expired
  if (loginResult.isPasswordExpired()) {
   System.out
     .println("An error has occurred. Your password has expired.");
   return false;
  }
  binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,
    loginResult.getServerUrl());
  System.out.println(loginResult.getServerUrl());
  SessionHeader sh = new SessionHeader();
  sh.setSessionId(loginResult.getSessionId());
  binding.setHeader(new SforceServiceLocator().getServiceName()
    .getNamespaceURI(), "SessionHeader", sh);
  return true;
 }

 /**
  * Create the RestConnection used to call Bulk API operations.
  */
 private RestConnection getRestConnection()
   throws ConnectionException, AsyncApiException {

  ConnectorConfig config = new ConnectorConfig();
  config.setSessionId(loginResult.getSessionId());
  String soapEndpoint = loginResult.getServerUrl();
  String apiVersion = "17.0";
  String restEndpoint = soapEndpoint.substring(0, soapEndpoint
    .indexOf("Soap/"))
    + "async/" + apiVersion;
  System.out.println(restEndpoint);
  config.setRestEndpoint(restEndpoint);
  config.setCompression(true);
  config.setTraceMessage(false);
  RestConnection connection = new RestConnection(config);
  return connection;
 }

 /**
  * Create a new job using the Bulk API.
  **
  * @param sobjectType
  *            The object type being loaded, such as "Account"
  * @param connection
  *            RestConnection used to create the new job.
  * @return The JobInfo for the new job.
  * @throws AsyncApiException
  */
 private JobInfo createJob(String sobjectType, RestConnection connection)
   throws AsyncApiException {
  JobInfo job = new JobInfo();
  job.setObject(sobjectType);
  job.setOperation(OperationEnum.insert);
  job.setContentType(ContentType.CSV);
//  System.getProperties().put("proxySet", "true");
//  System.getProperties().put("http.proxyHost", "proxy");
//  System.getProperties().put("http.proxyPort", "8080");
  job = connection.createJob(job);
  System.out.println(job);
  return job;
 }

 private List<BatchInfo> createBatchesFromCSVFile(RestConnection connection,
   JobInfo jobInfo, String csvFileName) throws IOException,
   AsyncApiException {
  List<BatchInfo> batchInfos = new ArrayList<BatchInfo>();
  BufferedReader rdr = new BufferedReader(new InputStreamReader(
    new FileInputStream(csvFileName)));
  // read the CSV header row
  byte[] headerBytes = (rdr.readLine() + "\n").getBytes("UTF-8");
  int headerBytesLength = headerBytes.length;
  File tmpFile = File.createTempFile("bulkAPIInsert", ".csv");
  // Split the CSV file into multiple batches
  try {
   FileOutputStream tmpOut = new FileOutputStream(tmpFile);
   int maxBytesPerBatch = 10000000; // 10 million bytes per batch
   int maxRowsPerBatch = 10000; // 10 thousand rows per batch
   int currentBytes = 0;
   int currentLines = 0;
   String nextLine;
   while ((nextLine = rdr.readLine()) != null) {
    byte[] bytes = (nextLine + "\n").getBytes("UTF-8");
    // Create a new batch when our batch size limit is reached
    if (currentBytes + bytes.length > maxBytesPerBatch
      || currentLines > maxRowsPerBatch) {
     createBatch(tmpOut, tmpFile, batchInfos, connection,
       jobInfo);
     currentBytes = 0;
     currentLines = 0;
    }
    if (currentBytes == 0) {
     tmpOut = new FileOutputStream(tmpFile);
     tmpOut.write(headerBytes);
     currentBytes = headerBytesLength;
     currentLines = 1;
    }
    tmpOut.write(bytes);
    currentBytes += bytes.length;
    currentLines++;
   }
   // Finished processing all rows
   // Create a final batch for any remaining data
   if (currentLines > 1) {
    createBatch(tmpOut, tmpFile, batchInfos, connection, jobInfo);
   }
  } finally {
   tmpFile.delete();
  }
  return batchInfos;
 }

 private void createBatch(FileOutputStream tmpOut, File tmpFile,
   List<BatchInfo> batchInfos, RestConnection connection,
   JobInfo jobInfo) throws IOException, AsyncApiException {
  tmpOut.flush();
  tmpOut.close();
  FileInputStream tmpInputStream = new FileInputStream(tmpFile);
  try {
   BatchInfo batchInfo = connection.createBatchFromStream(jobInfo,
     tmpInputStream);
   System.out.println(batchInfo);
   batchInfos.add(batchInfo);
  } finally {
   tmpInputStream.close();
  }
 }

 private void closeJob(RestConnection connection, String jobId)
   throws AsyncApiException {
  JobInfo job = new JobInfo();
  job.setId(jobId);
  job.setState(JobStateEnum.Closed);
  connection.updateJob(job);
 }

 private void awaitCompletion(RestConnection connection, JobInfo job,
   List<BatchInfo> batchInfoList) throws AsyncApiException {
  long sleepTime = 0L;
  Set<String> incomplete = new HashSet<String>();
  for (BatchInfo bi : batchInfoList) {
   incomplete.add(bi.getId());
  }
  while (!incomplete.isEmpty()) {
   try {
    Thread.sleep(sleepTime);
   } catch (InterruptedException e) {
   }
   System.out.println("Awaiting results..." + incomplete.size());
   sleepTime = 10000L;
   BatchInfo[] statusList = connection.getBatchInfoList(job.getId())
     .getBatchInfo();
   for (BatchInfo b : statusList) {
    if (b.getState() == BatchStateEnum.Completed
      || b.getState() == BatchStateEnum.Failed) {
     if (incomplete.remove(b.getId())) {
      System.out.println("BATCH STATUS:\n" + b);
     }
    }
   }
  }
 }

 private void checkResults(RestConnection connection, JobInfo job,
   List<BatchInfo> batchInfoList) throws AsyncApiException,
   IOException {
  // batchInfoList was populated when batches were created and submitted
  for (BatchInfo b : batchInfoList) {
   CSVReader rdr = new CSVReader(connection.getBatchResultStream(job
     .getId(), b.getId()));
   List<String> resultHeader = rdr.nextRecord();
   int resultCols = resultHeader.size();
   List<String> row;
   while ((row = rdr.nextRecord()) != null) {
    Map<String, String> resultInfo = new HashMap<String, String>();
    for (int i = 0; i < resultCols; i++) {
     resultInfo.put(resultHeader.get(i), row.get(i));
    }
    boolean success = Boolean.valueOf(resultInfo.get("Success"));
    boolean created = Boolean.valueOf(resultInfo.get("Created"));
    String id = resultInfo.get("Id");
    String error = resultInfo.get("Error");
    if (success && created) {
     System.out.println("Created row with id " + id);
    } else if (!success) {
     System.out.println("Failed with error: " + error);
    }
   }
  }
 }

}

In the above Source code Login is OK, after that creating Job with Restful connection error occured

Bulk API need to set Proxy ?? ,Because i am running this application in Proxy network.

 

 

 

Please Help

 

Thanks and Regards

Thanga

Message Edited by thangasan@yahoo on 10-18-2009 11:24 PM

Hi

 

 Custom Setting List ,Name field if we enter more then 5 Double byte char then it gives error
Sample data
  関根 秀治

 

 Is there any restriction in Name field ? For Single bytes its accepting 38 Char.

 

 It seems 1 double bytes its calculating 9 char .So we can enter 4 Double bytes and 2 Char like this.

 

 

An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience.

Thank you again for your patience and assistance. And thanks for using salesforce.com!

Error ID: 1700040002-861 (91623632)

 

 

Thanks and Regards

Thanga

Hai

 

  Any one confirm Custom Setting Data can be insert by Apex DML Operation ?

  Because i am getting the below Error during Insert.( Using Apex Batch I am inserting ).

 

System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: 1512696965-168 (489760386): []

Thanks and Regards

Thangaraj S

 

I'm using the apex InputFile standard component to allow users to attach images to one of my custom objects.

 

There seems to be a limit on the file name size, but I can't find anything in the docs or force sites to confirm this.

 

If the file name is greater than 81 characters, I get redirected to the salesforce "an error has occurred" page, but I don't get any warning emails etc., nor can I trap this error as it is happening before hitting my controller. 

 

Has anyone else seen this?

I am trying to display a field in a standard related list (of a custom object) based on a filtering condition, i.e. make it visible only for specific values of another field. What is the easiest way to do this?

 

 

 

Thanks in advance

  • August 26, 2009
  • Like
  • 0

Hello

 

By looking at the blogs and discussion boards i got the logic to work.

 

And i've spent quite some time already and cannot getting code coverage more than 68%. To deploy this to production i should have 75% coverage.

 

Can someone please help with the test methods for the below code?..Thanks

public class Account_Controller { Id AcctId = ApexPages.currentPage().getparameters().get('id'); Public Boolean errormsg; private String searchText; public string AName; Public Account acctName; public Boolean geterrormsg(){ return errormsg;} public List<AccountResult> AccountResults{get; set;} public List<AccountResult> getAccResult() { return AccountResults; } public string getSearchText() { return AName; } public void setSearchText (String searchText) { this.searchText = searchText; } public PageReference continue1() { String MstAcctid; String DupeAcctid; if(AccountResults!=null) { for(AccountResult AResult : getAccResult()) { if(AResult.master_selected == true) { MstAcctid=AResult.id; } if(AResult.duplicate_selected == true) { DupeAcctid=AResult.id; } } } System.debug('Mst Acct '+MstAcctid); System.debug('Duplicate Account '+DupeAcctid); if(MstAcctid==DupeAcctid) { errormsg=true; return null; } else { errormsg=false; PageReference Duplicate_step2Page = new PageReference('/Apex/Account_page2?MastId='+MstAcctid+'&DupeId='+DupeAcctid); Duplicate_step2Page.setRedirect(true); return Duplicate_step2Page; } } public PageReference init() { acctName=[Select Name from Account where id=:AcctId]; AName=acctName.Name; return null; } public List<Account> search1() { AccountResults= new List<AccountResult>(); for (Account account : [select Id, Name, Type, BillingStreet,Billingcity,BillingState,BillingPostalCode,Owner.Name from Account where Name like: searchText+'%']) { AccountResults.add(new AccountResult(account)); } return null; } public Class AccountResult { public Account Acc { get; set; } public Boolean selected { get;set;} public string id {get;set;} public string Name {get;set;} public Boolean master_selected { get; set; } public Boolean duplicate_selected { get; set; } public AccountResult(Account a) { Acc=a; id=a.id; Name=a.Name; selected=false; } } public void SelectAccount() { for (AccountResult acc : AccountResults) { if (acc.master_selected) { if(acc.duplicate_selected) { } } } } }

 

public static testMethod void results() { Account testAccount =new Account(Name='Sample2',RecordTypeid='012300000000RFTD',NumberOfEmployees=10,ownerid='00540000000TRFG); insert testAccount ; ApexPages.currentPage().getParameters().put('id', testAccount.id ); Account_Controller test=new Account_Controller(); test.init(); test.setSearchText('Tree'); String searchText = test.getSearchText(); test.getSearchText(); test.search1(); test.continue1(); }

 

  • August 18, 2009
  • Like
  • 0

Hai

 

I have written trigger for sending Email
when i use setHtmlBody with Japanese Character the Email having Junk Character
Any one have this problem ? Any Idea to solve this ?

 

Thanks

Thanga 

 

By Using <apex:relatedList list="" /> with Standard controller , related list automatically come the screen. Can any body have any idae how it will work if we are using custom controller. or is any documentation how exactly this tag is working.

Thanks inAdvance,

Raj

Hello,


I want to write a Visualforce page, and write out the data explicitly rather than use <apex:detail />.

 

The problem I'm having is I can't seem to find an example of defining # columns to print out the data.

 

In the Pages Developer Guide, I see examples of <apex:pageBlockTable>, which just loops printing data form a related list;  I see an example of <apex:dataTable>, but don't see how to setup the # of columns.

 

Can someone tell me out to get started.  For example, if I wanted to print out Contact details similar to how <apex:detail /> woudl output it, can you give me the first few lines of the Visualforce code?

 

Thanks,


AT

 

 

Hi,

 

I have this query in my apex class:

actvty= [ SELECT (SELECT ActivityDate, Description,Subject,who.name from ActivityHistories order by ActivityDate desc ) FROM Contact WHERE Id in :contid]; return actvty;

I am not sure how do I display this result in Visual force page. I tried the follwing but give me error.(Error: Invalid field Subject for SObject Contact)

<apex:pageBlockTable value="{!actvty}" var="t" rendered="{!NOT(ISNULL(actvty))}" > <apex:column value="{!t.Subject}"/> <apex:column value="{!t.Who.Name}"/> <apex:column value="{!t.ActivityDate}"/> </apex:pageBlockTable> <apex:outputLabel value="No records to display" rendered="{!(ISNULL(actvty))}" styleClass="noRowsHeader"></apex:outputLabel> </apex:pageblock>

 

Could you please help me ?

 

Message Edited by das on 08-03-2009 04:11 PM
Message Edited by das on 08-05-2009 03:47 PM

I'm trying to determine the default tab of a TabPanel based on ProfileID, but I can't figure it out. Here's the code in my page, with the If statement based on Profile.

 

<apex:tabPanel switchType="client" selectedTab="{!if($User.ProfileId!='00e00000006ore5', 'name5', 'name2')}"
tabClass="activeTab" inactiveTabClass="inactiveTab">

 

Basically for the default selectedTab, if the profile isn't the hardcoded id, I want it to show "name5", otherwise show "name2".

 

If I hardcode "name5" in, it works. I've also tried using {!$Profile.Name}.

 

Any help is appreciated.

 

Chris

 

 

I want to pass one parameter when user clicks on a command button.

 

I tried the following

 

                   <apex:commandButton action="{!registerForEvent}" value="Register" title="Register">
                        <apex:param name="eventId" value="{!r.id}" assignTo="{!eventId}"/>
                    </apex:commandButton>    

 

It does not work. The eventid value is coming as null in the controller. 

 

I was searching through the posts and found a few that says that this is a bug and parameters cannot be passed with command button. Some posts say, it works using assignTo attribute and having proper getter and setter methods for the assignTo variable. It is not working for me.

 

Is it working for anyone? Please let me know.

 

  • July 29, 2009
  • Like
  • 0

Hi:

 

I'm new to Visualforce and I'm trying to retrieve the size of a VisualforceArrayList.

 

I'm aware that I can use the <apex:repeat> component this way:

 

<apex:repeat value="{!Opportunity.OpportunityLineItems}" var="line">
  <tr>
   <td>{!line.PricebookEntry.ProductCode}</td>
   <td>{!line.PricebookEntry.Name}</td>
   <td>{!line.Quantity}</td>
   <td><apex:OutputField value="{!line.UnitPrice}"/></td>
   <td><apex:OutputField value="{!line.TotalPrice}"/></td>
 </tr>
</apex:repeat>

 

But what if I just want to know the number of LineItems inside my Opportunity.OpportunityLineItems VisualforceArrayList?

 

Is there a way to achieve this?

Something like .size() for ArrayLists or .length for Arrays in Java?

 

The other problem I have is that I'm using a Professional Edition License and it seems that I'm not able to create a Visualforce Custom Controller so I need to do it from the actual visualforce page.

 

Help would be very appreciated.

 

 

 

  • July 29, 2009
  • Like
  • 0

I have a trigger that needs to get the number of days between the created date of the event and the actvity date and put the result into another field

 

I keep receieving this message:

 Error: Compile Error: Method does not exist or incorrect signature: [Datetime].daysBetween(Date) at line 9 column 33

 

 

 

trigger Event_Before_Insert on Event (before insert)
    {
        for( Event currentEvent : Trigger.new )
        {
        datetime CreatedDate =CurrentEvent.CreatedDate;
        date ActivityDate =CurrentEvent.ActivityDate;

        
         Integer numberofDays = CreatedDate.daysBetween(ActivityDate);
       
         CurrentEvent.Day_Count__c = numberofDays;


       }

}

Message Edited by bikla78 on 07-29-2009 12:04 PM

Hello

 

I have a form that contains an inputtext and a commandlink that submits the form when clicked. I have noticed that if I press the enter key after entering text in the inputtext the page just refreshes. If I change the commandLink to a commandButton the form does submit, but I have certain reasons for using commandLink, so this is not feasible.

 

I have noticed this behaviour in another form on a seperate page too. Any ideas?

 

Wes 

I have a custom search Visualforce page (not tied to a specific object). I would like a seperate tab just for this custom search. Is there anyway to create a tab (not link to an object) from a Visualforce page?

 

If not what is the best way to get the link somewhere in the UI where it is easily accessible? Thanks 

I am creating a VF page on a standard controller. I'd like to create a button on the page that opens the new Record input screen (similar to the one on any tab home page). However, I can't find the correct action syntax for my commandButton.

 

Is this feature actually available for VF?

 

Many thanks,

Guy

I have the following code in one of the controller extension methods:

 

confirm() { 

PageReference p = Page.offbsubmit;

p.setRedirect(true);

return p;

}

 

I am testing the above code in testMethod using the following statement..

 

PageReference q = test.confirm();

PageReference s = Page.offbsubmit;

system.assertEquals(q, s); // getting an exception here!!

 

I am getting the following exception:

 

System.Exception: Assertion Failed: Expected: System.PageReference[/apex/offbsubmit], Actual: System.PageReference[/apex/offbsubmit] 

 

which doesnt make anysense to me because the expected and the actual values are the same..any help?

 

Message Edited by mallikam on 07-28-2009 11:10 AM