No Viable Alternative at character ' ' - salesforce

Hi i am getting the following error in this code
/*
Class : CreateMobileChatterCntrl
Description : Post Chatter on Contact.
Developed by : Harish Khatri(Appirio Offshore)
Created Date : June 2, 2012
*/
public without sharing class CreateMobileChatterCntrl {
public final Id ContactID{get;set;}
public String message{get;set;}
public boolean isSuccess{get;set;}
public boolean throwError{get;set;}
public String deviceType{get;set;}
//----------------------------------------------------------------------------
//constructor
//----------------------------------------------------------------------------
public CreateMobileChatterCntrl() {
throwError = false;
isSuccess = false;
if( ApexPages.CurrentPage().getParameters().get('id') != null){
ContactID = ApexPages.CurrentPage().getParameters().get('id');
}
String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT');
if(userAgent.contains('iPhone'))
deviceType = 'iPhone';
//else if(userAgent.contains('Android')) deviceType = 'Android';
}
//----------------------------------------------------------------------------
// Post the chatter on contact
//----------------------------------------------------------------------------
public Pagereference save() {
if(message == null || message ==''){
throwError = true;
return null;
}
FeedItem feedItem = new FeedItem();
feedItem.ParentId = ContactID;
feedItem.Body = message;
try {
insert feedItem;
isSuccess = true;
} catch(Exception e){}
return null;//new PageReference('/' + ContactID);
}
public Pagereference cancel() {
return new PageReference('/' + ContactID);
}
}
public final Id ContactID{get;set;} at this line i am getting the error No Viable Alternative at character ' '.can any one please help why i am getting this error??

Some of the single quote characters in your class file are invalid --- perhaps because you copied and pasted the code from somewhere else. I've had this happen many times before when I've copied code from elsewhere. Starting with the quotes in: message == '' , i'd delete the single quotes, retype them, and resave your file. Repeat for all single quotes (or do a find and replace).

Related

SalesForce: Classic to Lighting

Apologies if my question my be so dumb but my programming skills are really limited and I'm on a hurry for a PoC.
I have the apex class below which was developed for Classic. I would like to make it work with lighting and I'm not sure if the only thing I need to replace are the url's. I have created a developer account for my PoC and everytime I launch the class I'm redirected to Classic.
public class LookupByUrlParamController {
String accountName;
String accountNumber;
String phone;
String website;
String email;
String socialhandle;
public LookupByUrlParamController () { }
public String redirectToAccount() {
Account account;
Map<String,String> params = ApexPages.currentPage().getParameters();
if(params.size() > 0) {
accountName = params.get('account_name');
accountNumber = params.get('account_number');
phone = params.get('phone');
website = params.get('website');
email = params.get('email');
socialhandle = params.get('SocialHandle');
}
try {
if(accountName != null) {
account = [select ID from Account where name = :accountName limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(accountNumber != null) {
account = [select ID from Account where AccountNumber = :accountNumber limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(phone != null) {
String npa;
String nnx;
String extension;
// Added logic for NA phone numbers
if (phone.length() == 10) {
npa = phone.substring(0,3);
nnx = phone.substring(3,6);
extension = phone.substring(6,10);
phone = '(' + npa + ') ' + nnx + '-' + extension;
}
account = [select ID from Account where phone = :phone limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(website != null) {
account = [select ID from Account where website = :website limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(email != null) {
account = [select ID from Account where email__c = :email limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(socialhandle != null) {
account = [select ID from Account where SocialHandle__c = :socialhandle limit 1];
}
} catch (System.queryException e) {//no entry found for twitter handle lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
String accountUrl;
if(account != null) {
accountUrl = '/' + account.Id;
} else {
accountUrl = '/';
}
return accountUrl;
}
public static testMethod void testLookupByUrlParamAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = 'Avaya';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamInvalidAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');
}
public static testMethod void testLookupByUrlParamPhone() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamWherePhoneNumberIs10Chars() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234567891';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');//no record found
}
public static testMethod void testLookupByUrlParamInvalidPhoneNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000015EKVPIA4');
}
public static testMethod void testLookupByUrlParamAccountNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountNumber = '4321';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParam() {
LookupByUrlParamController controller = new LookupByUrlParamController();
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/');
}
}
In addition if anyone can tell where to being looking in the documentation to simply launch to new customer record form, or what are the redirect URLS?
It's not quite clear what you mean by
everytime I launch the class I'm redirected to Classic
However, this code appears not to have been touched in quite a number of years and there's several things you ought to change.
You are hard-coding non-My Domain Salesforce instance URLs (na7.salesforce.com). You should instead use URL.getSalesforceBaseUrl().toExternalForm(), and you'll need to turn on My Domain sooner or later.
You are using Classic-format URLs, which still work but will result in additional redirects. The Lightning equivalent for the "Create new Account" URL is lightning/o/Account/new and for a specific record is lightning/r/Account/<Id>/view. When you build Lightning components, you can use the navigation service to get these URLs dynamically.
You have inline test methods, which haven't been allowed since an API version well before I started on the platform. Break those out into a separate test class.

Compile Error: Field expression not allowed for generic SObject at line 33 column 69

I am trying to write a generic controller which will work for several different object types, but when I try to access custom fields from those objects, I get the following error:
Compile Error: Field expression not allowed for generic SObject at line 33 column 69
Here's my generic controller code:
public with sharing class PhotoUploadController {
public Attachment objAttach{get;set;}
public sObject sobj{get;set;}
public string ObjectName {get;set;}
public Decimal Height{get;set;}
public Decimal Width {get;set;}
Public List<Attachment> lstAttachment {get;set;}
public String setObjectType(sObject newObj)
{
this.ObjectName = newObj.getSObjectType().getDescribe().getName();
return(this.ObjectName );
}
public String getObjectType()
{
return(this.ObjectName);
}
public PhotoUploadController (ApexPages.StandardController controller)
{
objAttach=new Attachment();
lstAttachment= new List<Attachment>();
sobj = controller.getRecord();
if(sobj.id!=null){
sobj = Database.query('select id,name,Image_Attachment_ID__c from ObjectName where id=:sobj.id');
}
if(sobj.Image_Attachment_ID__c!=null){
lstattachment=[SELECT id,body from Attachment where Id=:sobj.Image_Attachment_ID__c limit 1];
if(lstattachment.size()>0)
{
objAttach=lstattachment[0];
}
}
}
public pageReference savePhoto(){
sobj.HeightOfPhoto__c=Height;
sobj.WidthOfPhoto__c=Width;
try {
if (!Schema.sObjectType.sobjectName.isUpdateable())
{
return null;
}
String contentType;
if(objAttach.ContentType !=null){
contentType=objAttach.ContentType;
}
if(contentType !=null && (contentType == 'image/jpeg' || contentType == 'image/CR2' || contentType== 'image/jpg' || contentType== 'image/png' || contentType== 'image/bmp' || contentType== 'image/gif')){
//objAttach.body=body;
//objAttach.name=name;
if(objAttach.body!=null && objAttach.name!=null && sobj.id !=null){
If(objAttach.Id==null)
objAttach.parentId=sobj.id;
if(!Schema.sObjectType.Attachment.isUpdateable()){
return null;
}
try{
upsert objAttach;
sobj.Image_URL__c=URL.getSalesforceBaseUrl().toExternalForm()+'/servlet/servlet.FileDownload?file='+objAttach.id;
sobj.Image_Attachment_ID__c= objAttach.id;
objAttach =null;
if (!Schema.sObjectType.ObjectName.isUpdateable()){
return null;
}
upsert sobj;
}
catch (DMLException e) {
if(e.getMessage().contains('STORAGE_LIMIT_EXCEEDED')){
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Your orgnization Storage Limit has been exceeded, Please contact your Administrator.'));
}else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
}
return null;
}finally {
objAttach = new Attachment();
}
}
}
else{
objAttach = new Attachment();
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please, Upload image file with extension .JPG .JPEG .BMP .PNG or .GIF'));
return null;
}
}
catch(Exception e) {
return null;
}
return new pagereference('/'+sobj.id);
}
}
Can someone explain this error message in a bit more detail? How do I access the fields I need from a generic SObject type?
There are couple issues in your code, but the cause of the reported error message is this snippet:
sobj.Image_Attachment_ID__c
You've not specified what type of SObject you are expecting, so there is no way to know:
If the SObject in memory even has that field
What type of field it is
What metadata belongs with that field (if the field was a picklist, you may have several SObjects with the same field name, but with different picklist options, etc)
The get(fieldName) function may be useful to you in this scenario. You may end up with an exception (which you can catch) if the SObject doesn't have that field, and it's up to you to cast the value into the proper data type (since it'll only return an object), which could throw a casting error if the value is a datetime and you try to cast it to an Id, etc.
Another issue I spotted:
[SELECT id,body from Attachment where Id=:sobj.Image_Attachment_ID__c limit 1] will never return a value. I think you meant ParentId=:sobj.Image_Attachment_ID__c.

Rule__c : managerules does not exist or is not a valid override for action Edit.

i have a class in dev org with code is
name of class is ManageRules.cls
/**
* This class is used for creating and editing Rule
**/
public with sharing class ManageRules{
public Rule__c newrule {get;set;}
public String objType {get;set;}
public string SearchEvalRule {get;set;}
public string Descr {get;set;}
public List<SelectOption> objOptions {get;set;}
// public String descr {get;set;}
public boolean edit {get;set;}
String ruleId;
public ManageRules(Apexpages.StandardController stdcon){
ruleId = stdcon.getId();
newrule = new Rule__c();
objOptions = new List<SelectOption>();
edit=false;
/**
* Add standard Objects
*/
objOptions.add(new SelectOption('',''));
objOptions.add(new SelectOption('Account','Account'));
objOptions.add(new SelectOption('Contact','Contact'));
objOptions.add(new SelectOption('Opportunity','Opportunity'));
objOptions.add(new SelectOption('Case','Case'));
objOptions.add(new SelectOption('Lead','Lead'));
objOptions.add(new SelectOption('Campaign','Campaign'));
objOptions.add(new SelectOption('Quote','Quote'));
objOptions.add(new SelectOption('Product2','Product'));
//objOptions.add(new SelectOption('ForeCast','Forecast'));
Map<String, Schema.SObjectType> mapObj = Schema.getGlobalDescribe();
for(String objname:mapObj.keySet()){
Schema.SObjectType sobj = mapObj.get(objname);
Schema.DescribeSObjectResult descRes = sobj.getDescribe();
/**
* Add custom objects
*/
if(descRes.isCustom() && !descRes.isCustomSetting()){
String objLabel = descRes.getLabel();
objOptions.add(new SelectOption(objName,objLabel));
}
}
/* Edit Rule */
if(ruleId!=null){
edit=true;
newrule = [select name,object__c,Rule_Execution_Plan__c,Available__c,Evaluation_Rule__c,Description__c from rule__c where id=:ruleId];
if(newrule!=null){
objtype=newrule.object__c;
Descr =newrule.Description__c;
SearchEvalRule =newrule.Evaluation_Rule__c ;
}
}
}
Public List<SelectOption> getEvalRule() {
List<selectOption> options = new List<selectOption>();
options.add(new selectOption('', '- None -'));
Schema.DescribeFieldResult field = Rule__c.Evaluation_Rule__c.getDescribe();
for (Schema.Picklistentry picklistEntry : field.getPicklistValues())
{
options.add(new SelectOption(pickListEntry.getValue(),pickListEntry.getLabel()));
}
return options;
}
public PageReference saveRule(){
newrule.object__c = objtype;
newrule.Evaluation_Rule__c=SearchEvalRule;
newrule.Description__c= Descr;
try{
Database.upsert(newrule);
return(new PageReference('/'+newrule.id));
}
catch(Exception e){
ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,e.getDMLMessage(0));
ApexPages.addMessage(msg);
return null;
}
}
public PageReference saveAndNewRule(){
newrule.object__c = objtype;
newrule.Evaluation_Rule__c=SearchEvalRule;
newrule.Description__c= Descr;
edit=false;
try{
Database.upsert(newrule);
newrule = new Rule__c();
return(new PageReference('/apex/manageRules'));
}
catch(Exception e){
ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,e.getDMLMessage(0));
ApexPages.addMessage(msg);
return null;
}
}
}
i created an object its giving me error
Description Resource Path Location Type
Save error: Rule_c : managerules does not exist or is not a valid override for action Edit. Rule_c.object /RuleCriteria/src/objects line 0 Force.com save problem
my Rule__c object code segment where i am getting this error is :
<actionOverrides>
<actionName>Edit</actionName>
<content>ManageRules</content>
<skipRecordTypeSelect>false</skipRecordTypeSelect>
<type>Visualforce</type>
</actionOverrides>
i am unable to figure why its showing me this error its an existing project so i have to deploy it on my dev org .on others org its working perfectly fine.i first save this class code and then try to save this object code and getting this error.can any one please how to resolve this issue??

GWT Restlet Parameters Always Null

I am brand new to both REST and RESTlet- I got everything up and communicating last night but what I found this morning is that everything I pass into the server is always becoming null.
just as a sample app i have the following - a User Objectify entity (id, emailAddress, and version), and a RESTUserProxy object (id, emailAddress) - I wasn't originally sure if i could pass Objectify Entities back and after not being able to see anything switched it to the Proxy object - if i can get it to work this way I will try switching it back
the front end is as follows:
public interface RESTUserResourceProxy extends ClientProxy {
#Get
public void find(String emailAddress, Result<RESTUserProxy> callback);
#Put
public void persist(RESTUserProxy user, Result<Void> callback);
#Delete
public void delete(RESTUserProxy user, Result<Void> callback);
}
the backend code is as follows (this is currently extremely ugly - i got a little frustrated just trying to see something and put in a ton of sysouts)
public class RESTUserServerResource extends ServerResource implements RESTUserResource {
private final UserDao userDao;
public RESTUserServerResource() {
System.out.println("CREATED USER RESOURCE IMPL");
userDao = new UserDao();
}
#Override
#Get
public RESTUserProxy find() {
System.out.println("reference = " + getReference());
Form queryParams = getReference().getQueryAsForm();
System.out.println("query params = " + queryParams);
System.out.println("query = " + getQuery());
System.out.println("query string = " + getQuery().getQueryString());
String searchQuery = (String) getRequest().getAttributes().get("searchQuery");
System.out.println("search query = " + searchQuery) ;
return null;
// if (emailAddress == null) {
// return null;
// }
// System.out.println("user resource impl find [" + emailAddress + "]");
// final User user = userDao.find(emailAddress.getText());
// if (user != null) {
// System.out.println("found user ");
// return new RESTUserProxy(user.getId(), user.getEmailAddress());
// } else {
// System.out.println("found absolutely nothing");
// return null;
// }
}
#Override
#Put
public void persist(RESTUserProxy userProxy) {
System.out.println("user proxy = " + userProxy);
if (userProxy == null) {
return;
}
final User user = userDao.find(userProxy.getId());
user.setEmailAddress(userProxy.getEmailAddress());
user.setId(userProxy.getId());
userDao.persist(user);
}
#Override
#Delete
public void delete(RESTUserProxy userProxy) {
final User user = userDao.find(userProxy.getId());
userDao.delete(user);
}
}
what im having problems with is that eerythings coming through as null - a lot of other answers on here said to get the query to get the params - but here the query is null
below is the output of calling find and persist
reference = http://127.0.0.1:8888/users/123
query params = []
query = []
query string =
search query = null
i'm sure i'm doing something stupid here i just have no idea how to proceed right now. Any help as to what i'm doing wrong would be greatly appreciated.
This is due to GAE not supporting chunked encoding. See workaround here:
http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet/303-restlet.html#dsy303-restlet_gwt

Updating properties for multiple users

How do I update a list of different Telephone, IPPhone using this
static void Main(string[] args)
{
Console.Write("Enter userid : "); // I would pass this in from the first
//Field in the .csv file 2439009
String username = Console.ReadLine();
try
{
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + uid + ")";
search.PropertiesToLoad.Add("Telephone","IPPhone");
SearchResult result = search.FindOne();
if (result != null)
{
// create new object from search result
DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
// show existing title
Console.WriteLine("Current title : " + entryToUpdate.Properties["Telephone][0].ToString());
Console.Write("\n\nEnter new title : ");
// get new title and write to AD
String newTitle = Console.ReadLine();
entryToUpdate.Properties["Telephone"].Value = newTelePhone;
entryToUpdate.Properties["IPPhone"].Value = newIPPhone;
entryToUpdate.CommitChanges();
Console.WriteLine("\n\n...new title saved");
}
else Console.WriteLine("User not found!");
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
}
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("mydomain.dm.com");
ldapConnection.Path = "LDAP://OU=myusers,DC=sales,DC=US,DC=US";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
I'm guessing you've grabbed someone else's code and don't know how to use it?
You should understand that this code can (will?) cause serious server problems as the DirectoryEntry resources are not closed correctly.
Every DirectoryEntry variable in your Main method should be wrapped in a using(){} statement.
Try something like this:
You define a class CSVRecord which holds your data from the CSV - read that in using FileHelpers. The class looks like this:
public class CSVRecord
{
public string EmployeeNumber { get; set; }
public string TelephoneNumber { get; set; }
public string IPPhoneNumber { get; set; }
}
Once you've read that class in, you need to iterate over its elements, and do the update for each of them.
CSVRecord[] listOfEmployees = (read in via FileHelpers)
// define root for searching your user accounts
using (DirectoryEntry root = new DirectoryEntry("LDAP://dc=yourcompany,dc=com"))
{
// set up directory searcher to find users by employeeId
using (DirectorySearcher searcher = new DirectorySearcher(root))
{
searcher.SearchScope = SearchScope.Subtree;
// iterate over all entries in your list of employees
foreach (CSVRecord csvEntry in listOfEmployees)
{
searcher.Filter = string.Format("(&(objectCategory=user)(employeeId={0}))", csvEntry.EmployeeNumber);
// search for that employee
SearchResult result = searcher.FindOne();
// if found - access the DirectoryEntry
if (result != null)
{
DirectoryEntry foundUser = result.GetDirectoryEntry();
// update properties from values in CSV
foundUser.Properties["telephoneNumber"].Value = csvEntry.TelephoneNumber;
foundUser.Properties["ipPhone"].Value = csvEntry.IPPhoneNumber;
// save changes back to directory
foundUser.CommitChanges();
}
}
}
}
Does that work for you??

Resources