• Ashmi Patel
  • NEWBIE
  • 135 Points
  • Member since 2016
  • Aglowid IT Solutions

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 41
    Questions
  • 77
    Replies
i cant upload file from salesforce to google drive. This is my code for uploading file.

 public PageReference DriveUploadAuth()
    {
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = UserInfo.getUserId();
    
    try
        {
            insert document;
        }
    catch(DMLException e){
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
      return null;
    }
    finally {
      document.body = null; // clears the viewstate
      document = new Document();
    }
    
         PageReference pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;
         return pg;
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully'));
         return null;     
    }

it will redirect me. bt I cant upload documents on google drive
need help
Thnx,
Ashmi
The OAuth client was not found.
Request Details
access_type=online
approval_prompt=auto
client_id= 330962932624-vh4n83lj5ggkag1j2u5l6r307d2tn7uf.apps.googleusercontent.com
login_hint=xxxx@gmail.com
redirect_uri=https://calendar.google.com/calendar
response_type=code
scope=https://www.googleapis.com/auth/calendar
state=vcalender

i m using following class code:

public class CalenderConnect {
    private final string googleClientID = '  ';
    private final string googleSecretCode = ' ';
    private final string redirectURI = 'https://calendar.google.com/calendar';
   // private final string redirectURI = 'https://rpaglowid-dev-ed--c.ap2.visual.force.com/apex/googleCall';
    private string authorizationCode = '';
    private string state = '';
    private string accessToken;
    private string refreshToken;
    private string expiresIn;
    private string tokenType;
 
     public CalenderConnect(){
        authorizationCode = System.currentPageReference().getParameters().get('code');
        if(authorizationCode != null){
            state = System.currentPageReference().getParameters().get('state');
            accessToken = '';
                retrieveGoogleAccessToken();
                if(accessToken <> ''){
                    addCalendarEntry();
                }              
        }
    }

    public pageReference doGoogleConnectCall(){

        PageReference pr = new PageReference('https://accounts.google.com/o/oauth2/auth' +
            '?response_type=code' +
            '&client_id=' + googleClientID +
            '&redirect_uri=' + redirectURI +
            '&scope=https://www.googleapis.com/auth/calendar' +
            // '&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar' +
            '&state=' + 'vcalender ' +
            '&access_type=online' +
            '&approval_prompt=auto' +  //auto, force
            '&login_hint=xxxx@gmail.com');
            System.debug(pr);
        return pr;
    }
    private void retrieveGoogleAccessToken(){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        string endPointValue = 'https://accounts.google.com/o/oauth2/token';  
        req.setEndpoint(endPointValue);
     
        string bodyRequest = '';
        bodyRequest = 'code=' + EncodingUtil.urlEncode(authorizationCode, 'UTF-8');
        bodyRequest += '&client_id=' + EncodingUtil.urlEncode(googleClientID, 'UTF-8');
        bodyRequest += '&client_secret=' + EncodingUtil.urlEncode(googleSecretCode, 'UTF-8');
        bodyRequest += '&redirect_uri=' + EncodingUtil.urlEncode(redirectURI, 'UTF-8');
        bodyRequest += '&grant_type=authorization_code';
        req.setBody(bodyRequest);    
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length()));
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setMethod('POST');
        req.setTimeout(10000);
        HttpResponse res = h.send(req);  
        map<string, string> jsonValues = new map<string, string>();
     
        System.debug('Response Value:'+res.getBody());
        jsonValues = parseJSONToMap(res.getBody());
        if(jsonValues.containsKey('error')){
        }else{
            //Try to get a cell value in the Google Spreadsheet
            accessToken = jsonValues.get('access_token');
            refreshToken = jsonValues.get('refresh_token');
            expiresIn = jsonValues.get('expires_in');
            tokenType = jsonValues.get('token_type');        
        }    
    }
      private void addCalendarEntry(){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        string endPointValue = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
        //This end point does seem to work, but it is not creating an event, just creating a new calendar
        //endPointValue = 'https://www.googleapis.com/calendar/v3/calendars?key=' + googleClientID;
        req.setEndpoint(endPointValue);  
        string bodyRequest = '';
        bodyRequest = '{';
        bodyRequest += '\r\n';
        bodyRequest += '"summary": "Sales Call",';
        bodyRequest += '\r\n';
        bodyRequest += '"location": "Conference Room A",';
        bodyRequest += '\r\n';
        bodyRequest += '"start": {';
        bodyRequest += '\r\n';
        bodyRequest += '"dateTime": "2014-07-26T08:00:00.000-07:00",';
        bodyRequest += '\r\n';
        bodyRequest += '"timeZone": "America/Los_Angeles"';
        bodyRequest += '\r\n';
        bodyRequest += '},';
        bodyRequest += '\r\n';
        bodyRequest += '"end": {';
        bodyRequest += '\r\n';
        bodyRequest += '"dateTime": "2014-07-26T08:30:00.000-07:00",';
        bodyRequest += '\r\n';
        bodyRequest += '"timeZone": "America/Los_Angeles"';
        bodyRequest += '\r\n';
        bodyRequest += '},';
        bodyRequest += '\r\n';
        bodyRequest += '"recurrence": [';
        bodyRequest += '\r\n';
        bodyRequest += '"RRULE:FREQ=WEEKLY;UNTIL=20131226T000000Z"';
        bodyRequest += '\r\n';
        bodyRequest += '],';      
        bodyRequest += '\r\n';
        bodyRequest += '"attendees": [';
        bodyRequest += '\r\n';
        bodyRequest += '{';
        bodyRequest += '\r\n';
        bodyRequest += '"email": "xxxxx@gmail.com"';
        bodyRequest += '\r\n';
        bodyRequest += '}';
        bodyRequest += '\r\n';
        bodyRequest += ']';
        bodyRequest += '}';
     
        req.setBody(bodyRequest);    
        System.debug(bodyRequest);
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length()));
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');
        req.setMethod('POST');
        req.setTimeout(10000);
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
    }
 
    private map<string, string> parseJSONToMap(string JSONValue){
        JSONParser parser = JSON.createParser(JSONValue);
        map<string, string> jsonMap = new map<string, string>();
        string keyValue = '';
        string tempValue = '';
        while (parser.nextToken() != null) {
            if(parser.getCurrentToken() == JSONToken.FIELD_NAME){
                keyValue = parser.getText();
                parser.nextToken();
                tempValue = parser.getText();
                jsonMap.put(keyValue, tempValue);            
            }
        }
        return jsonMap;
    }
 
}
i got this error need help...
Here is the Apex Class

public class FileUploadController{
public Document document {get; set;}
public String url {get; set;}
public boolean hasImage {get; set;}
public static final String hasImage;
public static final String document;

public static void FileUpload()
    {
        hasImage = false;
        document = new document();
    }

public PageReference doUpload()
    {
if (document.body != null)
{
     System.debug('@@@@@@@@ document:' + document.name);
     if (document.name != null)
     {
         System.debug('@@@@@@@@ doSave');
         Document d = document;
         System.debug(document);
         System.debug('@@@@@@@@ document name: '+d.name);
         System.debug(d);
         d.folderid = UserInfo.getUserId(); //store in Personal Documents
         System.debug('@@@@@@@@ document folder id: '+d.folderid);
         d.IsPublic = true;
        try
        {
            insert d;
            url = DocumentUtil.getInstance().getURL(d);
            hasImage = true;
        }
        catch (Exception e)
        {
            ApexPages.addMessages(e);
            url = '';
        }
        d.body = null;
        System.debug('@@@@@@@@ document object id: '+d.id);
        String url = DocumentUtil.getInstance(d).getURL();
        System.debug('######## document content type: '+d.type);
    }
 }
     PageReference page = new PageReference('/apex/FileUpload');
     return page;

    }

/*  static testmethod void testFileUpload()
    {
        FileUpload fu = new FileUpload();
        fu.doUpload();
        fu.document.Name = 'test1';
        fu.document.Body = Blob.valueOf('test1');
        fu.doUpload();
    } */

 }


 
i m getting this error...
what can i do to solve this error
i m getting this error on this line
 var eventList = Calendar.Events.list(calendarId, optionalArgs).items;

need help
thanks,
Ashmi

 
i m referring this link : https://developer.salesforce.com/page/Google_Data_Authentication
nd i m getting this error....
need help
rhnx,
Ashmi
i made apex class for connecting salesforce with google drive...bt when redirecting on google drive page ...nd when i click in
DENY button ..it still redirecting me on drive page...
User-added image
i have written a apex class for connect salesforce with gmail....i have made a apex page nd put button which connect to gmail....
bt it gives an error "Error: invalid_request" and "Required parameter is missing: response_type"
need help,
Thnx
This is the class code...for gmail integration
And what should be gmailContent in this code???

public with sharing class GmailIntegrationController{
    public List<AccountWrapper> accountswrappers { get; set; }
    String code;
    String key;
    String secret;
    String redirect_uri;
    String CheckFlag;

public GmailIntegrationController(ApexPages.StandardController controller){
        init();
}
    public void init()
    {
        code=null;
        key = '';
        secret = '';
        redirect_uri = 'https://gmail.google.com';
        System.debug('shhdhshdhshdhshdhhd' + ApexPages.currentPage().getUrl());
        code = ApexPages.currentPage().getParameters().get('code');
        System.debug('dsdsjdsjdjsjdjsjdsjd' + code);
       accountswrappers = new List<AccountWrapper>();
            if(code != '' && code != null){
                authenticationAndUpload();
                    return;
            }
}
    public void authenticationAndUpload(){
        System.debug('codesdd:::' + code);
            if(code != '' && code != null)
            {
                System.debug('codesdd:::' + code);
                AccessToken();
            }
            }

public void AccessToken(){
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');
    req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
 System.debug('messageBody::::' + messageBody );
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
System.debug(' This is the reponse from google: ' + resp );
        String str = resp;
        List<String> lstStr = str.split(',');
        System.debug('@@@'+lstStr[0]);
        List<String> lstStr1 = lstStr[0].split(':');
        System.debug('###'+lstStr1[1]);
        String st = lstStr1[1].remove('"').trim();
        System.debug('@#@'+st);
        
        System.debug('JHSDHSDJSJDJSD'  + st + 'TETTETTETTE');
Http http = new Http();
        req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'text/csv');
        req.setHeader('Authorization','Bearer '+st);
        String contentGmail = gmailContent();
        req.setBody(contentGmail);  
        req.setTimeout(60*1000);
        HttpResponse respp = http.send(req);
}
public PageReference GmailAuth()
    {
        PageReference pg = new PageReference(GmailAuthUri (key , redirect_uri)) ;
        return pg;
    }
    
    public String GmailAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/v2/auth?'+
        'scope = https://gmail.google.com/' +
        'state=security_token%ObUT6axTPjcyVZRAb3e8MXtl71%26url%3Dhttps://oa2cb.example.com/myHome&'+
        'redirect_uri=' +uri+
        '&response_type=code&'+
        'client_id='+key+
        '&access_type=offline';
        
        return authuri;
    }
    
    
    private String gmailContent(){
    
        String messageBodies = 'Number ,PTC,Last,First,Mid,Gender,Nationality,DOB,Passport No,Email,Phone\r';
        messageBodies+= 'Hello, Test , test, Test,Test, Test, Test,TEst\r';
        return messageBodies;
    }
 
    public class AccountWrapper{
   
        public Account account{get;set;}
        
        public AccountWrapper(Account account) {
            
            this.account = account;
        }
    }
}

This is apex code ::

<apex:page standardController="Account" extensions="GmailIntegrationController" id="pageId" showHeader="true" sideBar="true">
     <apex:form id="form">
        <apex:pageBlock id="pBd">
        <apex:pageMessages id="msg"/>
         <apex:outPutPanel id="panelId2">     
                <apex:commandButton action="{!GmailAuth}" value="Connect" status="waitMsg"/>
                    </apex:outPutPanel>
                    <apex:outputpanel >
                <apex:actionstatus id="waitMsg">
                    <apex:facet name="start">
                        <div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb; height: 100%; background: rgba(0, 0, 0, 0.5); width: 100%;position:fixed;top:0px;">
                            <div class="waitingHolder" style="height:25px; width:175px; z-index: 100000;margin:0 auto;position:fixed;left:50%;    top:50%;    margin:-75px 0 0 -135px;border-radius: 5px;background:#ECECE3;padding:10px;text-align: center;vertical-align: middle;border: 1px solid #97CAFF;-moz-box-shadow: 3px 3px 4px #000;-webkit-box-shadow: 3px 3px 4px #000;box-shadow: 3px 3px 4px #000;">
                                <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." /> <span class="waitingDescription" style="color:black;">
                                    Please Wait..</span>
                            </div>
                        </div>
                    </apex:facet>
                </apex:actionstatus>
                </apex:outputpanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>
I m getting this error...Method must define a body at line 12 column 17

This is my class code
What should be my code??


public with sharing class GmailIntegrationController{
    public List<AccountWrapper> accountswrappers { get; set; }
    String code;
    String key;
    String secret;
    String redirect_uri;
    String CheckFlag;

public GmailIntegrationController(ApexPages.StandardController controller){
        init();
}
    public void init();
    {
        code=null;
        key = '195939611313-5cr46086hm5db9m17aqjuo6gqpok9a0j.apps.googleusercontent.com';
        secret = '2LX5IFSaXhh87gfjaLzz8tz1';
        redirect_uri = 'https://gmail.google.com';
        System.debug('shhdhshdhshdhshdhhd' + ApexPages.currentPage().getUrl());
        code = ApesPages.currentPage().getParameters().get('code');
        System.debug('dsdsjdsjdjsjdjsjdsjd' + code);
        accountWrappers = new List<AccountWrapper>();
            if(code != '' && code != null){
                authenticationAndUpload();
                    return;
            }
}
    public void authenticationAndUpload(){
        System.debug('codesdd:::' + code);
            if(code != '' && code != null)
            {
                System.debug('codesdd:::' + code);
                AccessToken();
            }
            }

public void AccesToken(){
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');
    req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
 System.debug('messageBody::::' + messageBody );
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
System.debug(' This is the reponse from google: ' + resp );
        String str = resp;
        List<String> lstStr = str.split(',');
        System.debug('@@@'+lstStr[0]);
        List<String> lstStr1 = lstStr[0].split(':');
        System.debug('###'+lstStr1[1]);
        String st = lstStr1[1].remove('"').trim();
        System.debug('@#@'+st);
        
        System.debug('JHSDHSDJSJDJSD'  + st + 'TETTETTETTE');
Http http = new Http();
        req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('');
        req.setHeader('content-type', 'text/csv');
        req.setHeader('Authorization','Bearer '+st);
        String contentGmail = gmailContent();
        req.setBody(contentGmail);  
        req.setTimeout(60*1000);
        HttpResponse respp = http.send(req);
}
public PageReference GmailAuth()
    {
        PageReference pg = new PageReference(GmailAuthUri (key , redirect_uri)) ;
        return pg;
    }
    
    public String GmailAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/v2/auth?'+
     'scope = https://gmail.google.com/' +
     'state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
     'redirect_uri=' +uri+
        '&response_type=code&'+
        'client_id='+key+
        '&access_type=offline';
        
        return authuri;
    }
    
    
    private String gmailContent(){
    
        String messageBodies = 'Number ,PTC,Last,First,Mid,Gender,Nationality,DOB,Passport No,Email,Phone\r';
        messageBodies+= 'Hello, Test , test, Test,Test, Test, Test,TEst\r';
        return messageBodies;
    }
 
    public class AccountWrapper{
   
        public Account account{get;set;}
        
        public AccountWrapper(Account account) {
            
            this.account = account;
        }
    }
}
this is my class code..
And getting this error
plz help...
thnx


public with sharing class SendTemplatedEmail{
public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients,
                          String templateApiName, ID targetObjId, Id whatId, ID orgWideEmailId,
                          Boolean saveAsActivity, Attachment[] attachList )
 {
 
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    
Id templateId;  
try {templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;}
catch (Exception e) {
  throw new UtilException ('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName +
                ' refer to Setup | Communications Templates ' + templateApiName);
}
    
    
    email.setToAddresses(toRecipients);
    email.setCcAddresses(ccRecipients);
    email.setTargetObjectId(targetObjId);
    email.setWhatId(whatId);
    email.setorgWideEmailAddressId(orgWideEmailId);
    email.setTemplateId(templateId);
    email.setSaveAsActivity(saveAsActivity);      
    
    System.debug(LoggingLevel.INFO,'** entered sendTemplatedEmail, to:' + toRecipients + ' cc:' + ccRecipients +  ' templateId:' + templateId + ' tagetObjId:' + targetObjId +
                    ' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);
    try {
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        return;
    }
    catch (EmailException e) {throw new UtilException('[U-02] sendTemplatedEmail error. ' + e.getMessage());}
 
}  
}
 
i created a userinterface for connect google calendar with salesforce...
bt when i add event in google calendar , salesforce calendar shows show one day early...
for example i add event on 12 january in google calendar.... in salesforce it shows on 11 january....


need help
thnx ,
Ashmi
this is class code:::

public class ParseTest{

    public String getParsedText() {
        return null;
    }


    public String textToParse { get; set; }
    private String walkThrough(DOM.XMLNode node) {
  String result = '\n';
  if (node.getNodeType() == DOM.XMLNodeType.COMMENT) {
    return 'Comment (' +  node.getText() + ')';
  }
  if (node.getNodeType() == DOM.XMLNodeType.TEXT) {
    return 'Text (' + node.getText() + ')';
  }
  if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
    result += 'Element: ' + node.getName();
    if (node.getText().trim() != '') {
      result += ', text=' + node.getText().trim();
    }
    if (node.getAttributeCount() > 0) {
      for (Integer i = 0; i< node.getAttributeCount(); i++ ) {
        result += ', attribute #' + i + ':' + node.getAttributeKeyAt(i) + '=' + node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i));
      }  
    }
    for (Dom.XMLNode child: node.getChildElements()) {
      result += walkThrough(child);
    }
    return result;
  }
  return '';  //should never reach here
}
private String parse(String toParse) {
  DOM.Document doc = new DOM.Document();      
  try {
    doc.load(toParse);    
    DOM.XMLNode root = doc.getRootElement();
    return walkThrough(root);
    
  } catch (System.XMLException e) {  // invalid XML
    return e.getMessage();
  }
}
}

this is apex page::

<apex:page controller="ParseTest" sidebar="false" showHeader="false" > <apex:form> <apex:inputtextarea cols="40" rows="20" value="{!textToParse}" /> <apex:inputtextarea cols="40" rows="20" id="result" value="{!parsedText}"/> <br /> <apex:commandButton value="Parse" action="{!parse}" reRender="result"/> </apex:form> </apex:page>

 
i cant generate apex code after parsing any of the WSDL file
Need Help
how can i connect xml file with apex class???

This is my Apex class:::

global class GoogleAppsRegistrationHandler implements Auth.RegistrationHandler
{
        global User createUser(Id portalId, Auth.UserData data)
        {
                         String email = data.email;
                        if (email == null) return null;

                            User u;
                            try {
                        u = [Select Id, FirstName, LastName, Email, Username from User Where Username = :email];
                                }  
                                   catch (Exception e){
                            return null;
                                                        }
                                            return u;
                                            }
global void updateUser(Id userId, Id portalId, Auth.UserData data){

}
}


This is my Xml file:::
 
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>27.0</apiVersion>
</ApexClass>
 
METHOD_NOT_ALLOWED
errorCode: METHOD_NOT_ALLOWED
message: HTTP Method 'POST' not allowed. Allowed are HEAD,GET


i m getting this error while using apex REST services
i m getting this in workbench
How can i develop a application which sync google calander with salesforce???
need help....

thnx,
Ashmi
LEN(ZIP_Code__c) > 0 &&
(Country__c = "USA" || Country__c = "US") &&
VLOOKUP(
$ObjectType.ZIP_Code__c.Fields.City__c,
$ObjectType.ZIP_Code__c.Fields.Name,
LEFT(ZIP_Code__c,5))
<> City__c

what is the error....??
thnx, in advance
Need Help.

public class FollowUpTaskTester {
    private static integer NUMBER_TO_CREATE = 4;
    private static String UNIQUE_SUBJECT =
                                    'Testing follow-up tasks';

    static testMethod void testCreateFollowUpTasks() {
        List<Task> tasksToCreate = new List<Task>();
        for (Integer i = 0; i < NUMBER_TO_CREATE; i++) {
            Task newTask = new Task(subject = UNIQUE_SUBJECT,
                    ActivityDate = System.today(),
                    Create_Follow_Up_Task__c = true );
            System.assert(newTask.Create_Follow_Up_Task__c);
            tasksToCreate.add(newTask);
        }

        insert tasksToCreate;
        System.assertEquals(NUMBER_TO_CREATE,
                            [select count()
                             from Task
                             where subject = :UNIQUE_SUBJECT
                             and ActivityDate = :System.today()]);

        System.assertEquals(NUMBER_TO_CREATE,
           [select count()
            from Task
            where subject =
           :FollowUpTaskHelper.getFollowUpSubject(UNIQUE_SUBJECT)
           and ActivityDate = :System.today()+1]);
    }

    static testMethod void assertNormalTasksArentFollowedUp() {
        List<Task> tasksToCreate = new List<Task>();
        for (integer i = 0; i < NUMBER_TO_CREATE; i++) {
            Task newTask = new Task(subject=UNIQUE_SUBJECT,
                                  ActivityDate = System.today(),
                                  Create_Follow_Up_Task__c = false);
            tasksToCreate.add(newTask);
        }

        insert tasksToCreate;
        System.assertEquals(NUMBER_TO_CREATE,
                            [select count()
                            from Task
                            where subject=:UNIQUE_SUBJECT
                            and ActivityDate =:System.today()]);

        System.assertEquals(0,
              [select count()
               from Task
               where subject=
               :FollowUpTaskHelper.getFollowUpSubject(UNIQUE_SUBJECT)
               and ActivityDate =:(System.today() +1)]);
    }

}

 
i m making a batchable class for reduce development efforts..i m referring cookbook of salasforce...nd i m getting this error
ERROR :: Invalid type: DMLResults

CODE:
global class batchRefresh implements Database.Batchable<Sobject>, Database.Stateful  {
    global final string query;
    global DMLResults unsuccessfuls;

        global batchRefresh(String q){
            Query=q;
            }
        global Database.QueryLocator start(Database.BatchableContext BC){
            unsuccessfuls= new DMLResults();
            return Database.getQueryLocator(query);
        }
        global void execute(Database.BatchableContext BC, LIST<SObject> scope){
            unsuccessfuls.add(Database.update(scope,false),scope);
        }
        global void finish(Database.BatchableContext BC) {
            unsuccessfuls.batchOnFinish(BC.getJobId());
        }
}


 
Here is my visualpage code..
 

<apex:page standardController="Account" showHeader="true"
      tabStyle="account" >
   <style>
      .activeTab {background-color: #236FBD; color:white;
         background-image:none}
      .inactiveTab { background-color: lightgrey; color:black;
         background-image:none}
   </style>
   <apex:tabPanel switchType="client" selectedTab="tabdetails"
                  id="AccountTabPanel" tabClass="activeTab"
                  inactiveTabClass="inactiveTab">   
      <apex:tab label="Details" name="AccDetails" id="tabdetails">
         <apex:detail relatedList="false" title="true"/>
      </apex:tab>
      <apex:tab label="Contacts" name="Contacts" id="tabContact">
         <apex:relatedList subject="{!account}" list="contacts" />
      </apex:tab>
      <apex:tab label="Opportunities" name="Opportunities"
                id="tabOpp">
         <apex:relatedList subject="{!account}"
                           list="opportunities" />
      </apex:tab>
      <apex:tab label="Open Activities" name="OpenActivities"
                id="tabOpenAct">
         <apex:relatedList subject="{!account}"
                           list="OpenActivities" />
      </apex:tab>
      <apex:tab label="Notes and Attachments"
                name="NotesAndAttachments" id="tabNoteAtt">
         <apex:relatedList subject="{!account}"
                           list="NotesAndAttachments" />
      </apex:tab>
   </apex:tabPanel>
</apex:page>
I am attempting to complete the Execute SOQL and SOSL Queries in the Developer Console Basics module and the challenge is creating logs that have nothing to do with the SOSL inline query that is requested. I have executed the following code in the Execute anonymous window and the challenge still does not show as completed.
 
List<List<sObject>> searchList = [FIND 'Mission Control' IN ALL FIELDS 
                                  RETURNING Contact(FirstName, LastName,
                                  Phone, Email, Description)];
Contact[] searchContacts = (Contact[])searchList[0];

for (Contact c : searchContacts) {
   System.debug(c.LastName + ',' + c.FirstName);
}

So even with the above the challenge still returns with an error of:
 
Challenge Not yet complete... here's what's wrong: 
Could not find the contact's name in the debug log. Be sure to run a query for your record, and to write your contact's name to the debug log using the System.debug() method.

 
i got this error need help...
Here is the Apex Class

public class FileUploadController{
public Document document {get; set;}
public String url {get; set;}
public boolean hasImage {get; set;}
public static final String hasImage;
public static final String document;

public static void FileUpload()
    {
        hasImage = false;
        document = new document();
    }

public PageReference doUpload()
    {
if (document.body != null)
{
     System.debug('@@@@@@@@ document:' + document.name);
     if (document.name != null)
     {
         System.debug('@@@@@@@@ doSave');
         Document d = document;
         System.debug(document);
         System.debug('@@@@@@@@ document name: '+d.name);
         System.debug(d);
         d.folderid = UserInfo.getUserId(); //store in Personal Documents
         System.debug('@@@@@@@@ document folder id: '+d.folderid);
         d.IsPublic = true;
        try
        {
            insert d;
            url = DocumentUtil.getInstance().getURL(d);
            hasImage = true;
        }
        catch (Exception e)
        {
            ApexPages.addMessages(e);
            url = '';
        }
        d.body = null;
        System.debug('@@@@@@@@ document object id: '+d.id);
        String url = DocumentUtil.getInstance(d).getURL();
        System.debug('######## document content type: '+d.type);
    }
 }
     PageReference page = new PageReference('/apex/FileUpload');
     return page;

    }

/*  static testmethod void testFileUpload()
    {
        FileUpload fu = new FileUpload();
        fu.doUpload();
        fu.document.Name = 'test1';
        fu.document.Body = Blob.valueOf('test1');
        fu.doUpload();
    } */

 }


 
i m referring this link : https://developer.salesforce.com/page/Google_Data_Authentication
nd i m getting this error....
need help
rhnx,
Ashmi
I m getting this error...Method must define a body at line 12 column 17

This is my class code
What should be my code??


public with sharing class GmailIntegrationController{
    public List<AccountWrapper> accountswrappers { get; set; }
    String code;
    String key;
    String secret;
    String redirect_uri;
    String CheckFlag;

public GmailIntegrationController(ApexPages.StandardController controller){
        init();
}
    public void init();
    {
        code=null;
        key = '195939611313-5cr46086hm5db9m17aqjuo6gqpok9a0j.apps.googleusercontent.com';
        secret = '2LX5IFSaXhh87gfjaLzz8tz1';
        redirect_uri = 'https://gmail.google.com';
        System.debug('shhdhshdhshdhshdhhd' + ApexPages.currentPage().getUrl());
        code = ApesPages.currentPage().getParameters().get('code');
        System.debug('dsdsjdsjdjsjdjsjdsjd' + code);
        accountWrappers = new List<AccountWrapper>();
            if(code != '' && code != null){
                authenticationAndUpload();
                    return;
            }
}
    public void authenticationAndUpload(){
        System.debug('codesdd:::' + code);
            if(code != '' && code != null)
            {
                System.debug('codesdd:::' + code);
                AccessToken();
            }
            }

public void AccesToken(){
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');
    req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
 System.debug('messageBody::::' + messageBody );
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
System.debug(' This is the reponse from google: ' + resp );
        String str = resp;
        List<String> lstStr = str.split(',');
        System.debug('@@@'+lstStr[0]);
        List<String> lstStr1 = lstStr[0].split(':');
        System.debug('###'+lstStr1[1]);
        String st = lstStr1[1].remove('"').trim();
        System.debug('@#@'+st);
        
        System.debug('JHSDHSDJSJDJSD'  + st + 'TETTETTETTE');
Http http = new Http();
        req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('');
        req.setHeader('content-type', 'text/csv');
        req.setHeader('Authorization','Bearer '+st);
        String contentGmail = gmailContent();
        req.setBody(contentGmail);  
        req.setTimeout(60*1000);
        HttpResponse respp = http.send(req);
}
public PageReference GmailAuth()
    {
        PageReference pg = new PageReference(GmailAuthUri (key , redirect_uri)) ;
        return pg;
    }
    
    public String GmailAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/v2/auth?'+
     'scope = https://gmail.google.com/' +
     'state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
     'redirect_uri=' +uri+
        '&response_type=code&'+
        'client_id='+key+
        '&access_type=offline';
        
        return authuri;
    }
    
    
    private String gmailContent(){
    
        String messageBodies = 'Number ,PTC,Last,First,Mid,Gender,Nationality,DOB,Passport No,Email,Phone\r';
        messageBodies+= 'Hello, Test , test, Test,Test, Test, Test,TEst\r';
        return messageBodies;
    }
 
    public class AccountWrapper{
   
        public Account account{get;set;}
        
        public AccountWrapper(Account account) {
            
            this.account = account;
        }
    }
}
i cant generate apex code after parsing any of the WSDL file
Need Help
how can i connect xml file with apex class???

This is my Apex class:::

global class GoogleAppsRegistrationHandler implements Auth.RegistrationHandler
{
        global User createUser(Id portalId, Auth.UserData data)
        {
                         String email = data.email;
                        if (email == null) return null;

                            User u;
                            try {
                        u = [Select Id, FirstName, LastName, Email, Username from User Where Username = :email];
                                }  
                                   catch (Exception e){
                            return null;
                                                        }
                                            return u;
                                            }
global void updateUser(Id userId, Id portalId, Auth.UserData data){

}
}


This is my Xml file:::
 
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>27.0</apiVersion>
</ApexClass>
 
METHOD_NOT_ALLOWED
errorCode: METHOD_NOT_ALLOWED
message: HTTP Method 'POST' not allowed. Allowed are HEAD,GET


i m getting this error while using apex REST services
i m getting this in workbench
LEN(ZIP_Code__c) > 0 &&
(Country__c = "USA" || Country__c = "US") &&
VLOOKUP(
$ObjectType.ZIP_Code__c.Fields.City__c,
$ObjectType.ZIP_Code__c.Fields.Name,
LEFT(ZIP_Code__c,5))
<> City__c

what is the error....??
thnx, in advance
https://developers.google.com/drive/web/manage-downloads

In the above link it is given that we have to make a GET request to the downloadUrl (which we get in the response when we upload the file) in order to get the file contents.

The downloadUrl which I got after uploading file to google drive is :
"downloadUrl": "https://doc-10-cc-docs.googleusercontent.com/docs/securesc/2butu3k0aok5svkleqovepe3uqqvauqr/9o0jdpikd3jl5krf0vgcacuhfl8gro0v/1408694400000/05688347114777583261/05688347114777583261/0B602YDdndVQ6LUxZRC0wX1ZtWWs?h=16653014193614665626&e=download&gd=true"

Now i am making GET request like this:

        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint(downloadURL);
        req.setHeader('content-type', 'text/plain');
        req.setHeader('Authorization','Bearer '+accessToken);
        req.setTimeout(60*1000);
        HttpResponse resp = http.send(req);

My problem is that, each time i upload the file i will get different downloadUrl such that it is difficult to change the remote site settings every time.
Any way to dynamically change the remote site setting? Please help me.