• roryok
  • NEWBIE
  • 0 Points
  • Member since 2010

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 3
    Replies

I have an app which logs in and scrapes Report CSV files to extract contacts. We have about 20 users. For ONE of those users, I'm getting the following error when the app tries to connect to salesforce

 

INVALID_CROSS_REFERENCE_KEY

 

User credentials are correct. 

 

All the info I can find on this online refers to trying to create or access folders or contacts. However, this error occurs before the app tries to do anything. It is happening at the login level. 

 

Can anyone help? 

  • February 03, 2012
  • Like
  • 0

Had some issues getting JSONObject to work and I just wanted to share my experiences here. The forum posts aren't much help for newbs like me (as they all relate to specific problems), and JSONObject doesn't come with any documentation. Here are a few things I wish someone had told me before I started out with it. 

 

 

  • JSONObject is ported from a java class of the same name. Some of the methods and objects have been deprecated, but remain in the code, commented out. You cannot use JSONArray at all. 

  • There are no other JSON Parsers / Libraries available for Apex. None I could find anyhow. 

  • The Apex TestMethods at the end of the file are the best place to learn how to access an object. 

  • Every reference to a JSONObject type has to be prefixed with "JSONObject". That might seem obvious to anyone who's done any OOP at all, but the aforementioned testmethods are internal to the class, so they don't need to use this reference. I found that a little confusing when trying to get sample code to work. Maybe there's a way to reference the library at the top, but I couldn't find it. 

I kept getting an error "Variable is not visible: data" when trying to access the data object of any value, so I had to change this 

 

    private map<string,value> data = new map<string,value>();

 to this

 

    public map<string,value> data = new map<string,value>();

 

which did the trick. Am I doing something wrong here? I'm hoping a developer will explain to me whats going on here - surely I must be accessing these values incorrectly. 

 

 

 

Here are some examples of how to access JSON using this library: 

 

String output = '';
String jsondata = '
{
	"set":"ww2 fighter aircraft",
	"planes":[
		{"name":"Messerschmitt Bf 109","max_speed":"640km/h","wingspan":"9.925m"},
		{"name":"Supermarine Spitfire","max_speed":"605km/h","wingspan":"11.23m"}
	]
}';

// initialize the JSONObject
JSONObject j = new JSONObject(new JSONObject.JSONTokener(jsondata));
output = j.getString('set') + '<br/>';
                
// without changing 'data' in JSONObject to 'public', the line below
// will throw a 'Variable is not visible: data' error

// get the data of j, get the object 'planes', extract an array of values (ie sub-objects) from 'planes'
JSONObject.value[] vs = j.data.get('planes').values;

// now we have a set of value objects. lets iterate through them
for(JSONObject.value o: vs){
   output += 'The ' 
	+ o.obj.getString('name') 
	+ ' had a wingspan of ' 
	+ o.obj.getString('wingspan') + '<br/>';
}


 

If anyone has any other advice or examples they'd like to add, please do. Also if any programmers can tell me why data is marked private in the class, that would be great. 

 

 

  • April 06, 2011
  • Like
  • 0

I'm currently using 'scraping' to extract report data from an exported CSV file. Currently this requires having the users username and password. 

 

I'd prefer to use OAuth. However, after coding together an OAuth solution I'm getting a login prompt whenever I attempt to access the CSV export link - does anyone know if this is possible with OAuth? Or is it something I can only do with a standard user/pass login? 

  • February 09, 2011
  • Like
  • 0

Hi Folks

 

I'm trying to use Oauth to connect to salesforce from a .NET app. I'm using DotNetOpenAuth at the moment, and having no luck. I can get twitter / google etc to work fine, but when I create a new consumer service for Salesforce, it just gives me an error (400 / Bad Request)

I'm using the InMemoryTokenManager, but before I get shouted at, let me re-iterate that twitter et al work fine this way. I do intent to replace the inmemorytoken manager with a database implentation, but for now I just want to get it working. 

 

The strange thing is, if I manually create the URL - https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=[consumer_key]&redirect_uri=[redirect_url] and enter it in the browser I end up at a salesforce  page to authorise the app to access my account - the one I expect to see should everything work. 

 

Is this expected behaviour? It seems like a security hole, but maybe I'm not understanding everything correctly. 

 

Any ideas where I'm going wrong? 

 

ConsumerCode - (well, the important part at least)

 

 

public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription
        {
            RequestTokenEndpoint = new MessageReceivingEndpoint("https://login.salesforce.com/services/oauth2/authorize", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://login.salesforce.com/services/oauth2/authorize", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            AccessTokenEndpoint = new MessageReceivingEndpoint("https://login.salesforce.com/services/oauth2/token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
        }; 

 

  OAuthController.cs
if (this.SFTokenManager != null)
            {
                var SF = new WebConsumer(SFConsumer.ServiceDescription, this.SFTokenManager);
                // Is Twitter calling back with authorization?
                var accessTokenResponse = SF.ProcessUserAuthorization();
                if (accessTokenResponse != null)
                {
                    this.SFAccessToken = accessTokenResponse.AccessToken;
                }
                else if (this.SFAccessToken == null)
                {
                    // If we don't yet have access, immediately request it.
                    SF.Channel.Send(SF.PrepareRequestUserAuthorization());                    
                }
                return View("SFIn");
            }
            else
            {
                return View("SFOut");
            }

 

 

The line I get my 400 at is 

 

 

// If we don't yet have access, immediately request it.
SF.Channel.Send(SF.PrepareRequestUserAuthorization());     

 

 

 

 

  • February 04, 2011
  • Like
  • 0

having a weird problem - I have a simple form which performs a POST via the apex HttpRequest object when a button is pressed, pulling a message from a textarea and posting it. When I add a simple dropdown above this, the page events don't seem to fire. The SendMessage method won't even log a message to the debug logs. Here's my code, in its simplest form:

VISUAL FORCE CODE

 

<apex:page id="MyPage" controller="MyClass">
    <h2>Enter message and press Send</h2>
    <br/><br/>
    <apex:form id="theForm2">   
        <apex:pageBlock title="ResultsSection">
		
        <apex:panelGrid columns="2">
		
            <apex:outputLabel value="Country:"/>
            <apex:selectList id="reports" value="{!countries}" size="1" required="true">
              <apex:selectOptions value="{!items}"/>
            </apex:selectList>
                
            <apex:outputLabel value="Message:"/> 
            <apex:inputTextarea cols="50" rows="5" value="{!MessageText}" />
                
            <apex:outputLabel value=" "/> 
            <apex:actionStatus id="btnSend">    
                <apex:facet name="stop">                                       
                    <apex:commandButton action="{!SendMessage}"  status="btnSend" value="Send Message" rerender="ResultsSection, Buttons"/>     
                </apex:facet>          
                <apex:facet name="start">     
                    <apex:commandButton action="{!SendMessage}" status="btnSend" value="Sending..." disabled="true" />
                </apex:facet> 
            </apex:actionStatus>
			
        </apex:panelGrid>
        </apex:pageBlock> 
    </apex:form>
</apex:page>

 

 

APEX CONTROLLER

 

 

public class MyClass {
    
    public String MessageText { get ; set ;}     
    
    public void SendMessage() 
    {
        try{
            System.debug('Sending...');   
			// Code to perform Http POST goes here...
        }catch (Exception e) {
            System.debug('Failing...' + e);             
        }
    }
    
    public List<SelectOption> getItems() {
        List<SelectOption> op = new List<SelectOption>();      
        op.add(new SelectOption('ie', 'Ireland'));
		op.add(new SelectOption('gb', 'United Kingdom'));
		op.add(new SelectOption('fr', 'France'));
		op.add(new SelectOption('de', 'Germany'));
        return op;
    }
        
    String[] countries = new String[]{};
        
    public String[] getCountries() { return countries; }
        
    public void setCountries(String[] countries) { this.countries = countries; }

}

 

 

 

If the VIsual Force code for the country Select List (the VF code, NOT the apex code!) is removed, the Apex code does not work. It throws no errors, and the page renders correctly, but pressing the button does nothing in this instance. 

 

Anyone got any ideas? I'm tearing my hair out here. 

 

PS: I know the selectlist isn't yet wired up to actually do anything, I thought I'd try and get it to not frak the entire page first =/

  • December 03, 2010
  • Like
  • 0

I'm trying to do a POST from within Apex - I can make the request successfully but no matter what way I add the data it doesn't get picked up by the app I'm sending to. Here's my code. 

 

HttpRequest req = new HttpRequest();
HTTPResponse res = new HTTPResponse();
Http http = new Http();     
String msg = '<message>Hello World!</message>';

// OR 
// String msg = 'post1=one&post2=two';

req.setEndpoint('http://mydomain.com/test.aspx');
req.setMethod('POST');            
req.setHeader('Content-Type', 'text/xml; charset=utf-8');  
req.setHeader('Content-Length', String.valueOf(msg.trim().length()));
res.setBody(msg);
res = http.send(req);    

Anyone got any ideas where I'm going wrong? I should clarify that this is successfully reaching and calling the target, so a post IS being performed, its just the body that's not going through

  • November 30, 2010
  • Like
  • 0

I'm in the process of developing a plugin for Salesforce which would allow a list of contacts to be exported based on a User Defined Report. 

 

I've found two ways to access the Report data, but neither are satisfactory: 

 

- The first method is to save the report data to a campaign, and then access that campaign. This involves too many user operations and is time consuming. 

 

- The second method is to perform a HttpRequest to the url for exporting CSV, but this seems like a very shaky way of doing things, especially since permissions must be added for the subdomain used by the export page (and these vary by geographical location)

 

Are there any other ways of accessing the report data, or of accessing the SOQL used to generate the User Defined Report? The report itself must contain the SOQL somewhere (or some abstracted for of it) in order to allow it to be run again. Any ideas? 

 

 

  • November 29, 2010
  • Like
  • 0

Had some issues getting JSONObject to work and I just wanted to share my experiences here. The forum posts aren't much help for newbs like me (as they all relate to specific problems), and JSONObject doesn't come with any documentation. Here are a few things I wish someone had told me before I started out with it. 

 

 

  • JSONObject is ported from a java class of the same name. Some of the methods and objects have been deprecated, but remain in the code, commented out. You cannot use JSONArray at all. 

  • There are no other JSON Parsers / Libraries available for Apex. None I could find anyhow. 

  • The Apex TestMethods at the end of the file are the best place to learn how to access an object. 

  • Every reference to a JSONObject type has to be prefixed with "JSONObject". That might seem obvious to anyone who's done any OOP at all, but the aforementioned testmethods are internal to the class, so they don't need to use this reference. I found that a little confusing when trying to get sample code to work. Maybe there's a way to reference the library at the top, but I couldn't find it. 

I kept getting an error "Variable is not visible: data" when trying to access the data object of any value, so I had to change this 

 

    private map<string,value> data = new map<string,value>();

 to this

 

    public map<string,value> data = new map<string,value>();

 

which did the trick. Am I doing something wrong here? I'm hoping a developer will explain to me whats going on here - surely I must be accessing these values incorrectly. 

 

 

 

Here are some examples of how to access JSON using this library: 

 

String output = '';
String jsondata = '
{
	"set":"ww2 fighter aircraft",
	"planes":[
		{"name":"Messerschmitt Bf 109","max_speed":"640km/h","wingspan":"9.925m"},
		{"name":"Supermarine Spitfire","max_speed":"605km/h","wingspan":"11.23m"}
	]
}';

// initialize the JSONObject
JSONObject j = new JSONObject(new JSONObject.JSONTokener(jsondata));
output = j.getString('set') + '<br/>';
                
// without changing 'data' in JSONObject to 'public', the line below
// will throw a 'Variable is not visible: data' error

// get the data of j, get the object 'planes', extract an array of values (ie sub-objects) from 'planes'
JSONObject.value[] vs = j.data.get('planes').values;

// now we have a set of value objects. lets iterate through them
for(JSONObject.value o: vs){
   output += 'The ' 
	+ o.obj.getString('name') 
	+ ' had a wingspan of ' 
	+ o.obj.getString('wingspan') + '<br/>';
}


 

If anyone has any other advice or examples they'd like to add, please do. Also if any programmers can tell me why data is marked private in the class, that would be great. 

 

 

  • April 06, 2011
  • Like
  • 0

I'm trying to do a POST from within Apex - I can make the request successfully but no matter what way I add the data it doesn't get picked up by the app I'm sending to. Here's my code. 

 

HttpRequest req = new HttpRequest();
HTTPResponse res = new HTTPResponse();
Http http = new Http();     
String msg = '<message>Hello World!</message>';

// OR 
// String msg = 'post1=one&post2=two';

req.setEndpoint('http://mydomain.com/test.aspx');
req.setMethod('POST');            
req.setHeader('Content-Type', 'text/xml; charset=utf-8');  
req.setHeader('Content-Length', String.valueOf(msg.trim().length()));
res.setBody(msg);
res = http.send(req);    

Anyone got any ideas where I'm going wrong? I should clarify that this is successfully reaching and calling the target, so a post IS being performed, its just the body that's not going through

  • November 30, 2010
  • Like
  • 0

I'm in the process of developing a plugin for Salesforce which would allow a list of contacts to be exported based on a User Defined Report. 

 

I've found two ways to access the Report data, but neither are satisfactory: 

 

- The first method is to save the report data to a campaign, and then access that campaign. This involves too many user operations and is time consuming. 

 

- The second method is to perform a HttpRequest to the url for exporting CSV, but this seems like a very shaky way of doing things, especially since permissions must be added for the subdomain used by the export page (and these vary by geographical location)

 

Are there any other ways of accessing the report data, or of accessing the SOQL used to generate the User Defined Report? The report itself must contain the SOQL somewhere (or some abstracted for of it) in order to allow it to be run again. Any ideas? 

 

 

  • November 29, 2010
  • Like
  • 0