Programatically fetch a list of all Salesforce Objects using apex in Salesforce - session

I want to fetch a list of all Salesforce objects.
I found this link
http://wiki.developerforce.com/index.php/Enterprise_Describe_Global
but there are some issues:
1) Missing session(Invalid session id)
To prevent this i appended the session key in the url also for the post request but it shows no request.
Error : Internal Server Error (500)
2) I found somewhere and added clientId along with the session header but again no response.
Error : Internal Server Error (500)
code sample of web request:
HttpRequest req = new HttpRequest();
Http http = new Http();
req.setMethod('POST');
req.setHeader('content-type','text/xml;charset=utf-8');
req.setHeader('Content-Length','1024');
req.setHeader('Host','na1.salesforce.com ');
req.setHeader('Connection','keep-alive');
req.setHeader('soapAction', 'getObjects');
String url = 'https://na1.salesforce.com/services/Soap/c/10.0/session_key';
String str = '<?xml version="1.0" encoding="utf-8"?> '+
'<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:enterprise.soap.sforce.com\">'+
'<soapenv:Header>'+
'<urn:SessionHeader>'+
'<urn:sessionId>'+'session_ID'+'</urn:sessionId>'+
'</urn:SessionHeader>'+
'<urn:CallOptions><urn:client>CLIENT_ID</urn:client></urn:CallOptions>'+
'</soapenv:Header>'+
'<soapenv:Body>'+
'<describeGlobal></describeGlobal>'+
'</soapenv:Body>'+
'</soapenv:Envelope>';
req.setEndpoint(url);
req.setBody(str);
HTTPResponse resp = http.send(req);
system.debug('response:::'+xml_resp);
Session_ID : I got this value from UserInfo.getSessionID();
client_ID : I tried following values : UserInfo.getUserID();/Secret token
but i couldnt make it a perfect call to get reaponse.
Hope somebody can help...

Why are you using an outbound web service call in Apex? Apex has native access to global describe information using Schema.getGlobalDescribe() - which is a much better way to access describe results.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_schema.htm has the full documentation for calling this from Apex.

Related

Response body is not returning from custom error responses in swagger Swashbuckle

I have integrated swagger to a dot.net core API application using Swashbuckle. When I execute an API via Swagger UI without providing credentials it is returning a "401- Unauthorized" response as expected.
But it is not showing the error response which I have configured to return as a custom error response as the body. It does returns the header as below image.
When I execute the same API via Postman it does return the custom error response as below.
What I need is, I need to see the custom error response body in the swagger UI as well.
In Postman,
In Swagger,
Same scenario with the 403 and 404 status codes.
After struggling a lot I have found the root cause to the issue.It is due to not having configure the Response Content type in the "app.UseStatusCodePages" middle ware.
// Custom status handling
app.UseStatusCodePages(async (StatusCodeContext context) =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.Formatting = Formatting.Indented;
int statusCode = context.HttpContext.Response.StatusCode;
***context.HttpContext.Response.ContentType = "application/json";*** // Added this line to solve the issue
await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(
new ErrorResponse((HttpStatusCode)statusCode,
ReasonPhrases.GetReasonPhrase(statusCode)
), settings));
});
Had to add "context.HttpContext.Response.ContentType = "application/json";" to fix the issue.

Get "API key is missing" error when querying account details to Mailchimp API 3.0 using RestSharp

When using RestSharp to query account details in your MailChimp account I get a "401: unauthorized" with "API key is missing", even though it clearly isn't!
We're using the same method to create our RestClient with several different methods, and in all requests it is working flawlessly. However, when we're trying to request the account details, meaning the RestRequest URI is empty, we get this weird error and message.
Examples:
private static RestClient CreateApi3Client(string apikey)
{
var client = new RestClient("https://us2.api.mailchimp.com/3.0");
client.Authenticator = new HttpBasicAuthenticator(null, apiKey);
return client;
}
public void TestCases() {
var client = CreateApi3Client(_account.MailChimpApiKey);
var req1 = new RestRequest($"lists/{_account.MailChimpList}/webhooks", Method.GET);
var res1 = client.Execute(req1); // works perfectly
var req2 = new RestRequest($"automations/{account.MailChimpTriggerEmail}/emails", Method.GET);
var res2 = client.Execute(req2); // no problem
var req3 = new RestRequest(Method.GET);
var res3 = client.Execute(req3); // will give 401, api key missing
var req4 = new RestRequest(string.Empty, Method.GET);
var res4 = client.Execute(req4); // same here, 401
}
When trying the api call in Postman all is well. https://us2.api.mailchimp.com/3.0, GET with basic auth gives me all the account information and when debugging in c# all looks identical.
I'm trying to decide whether to point blame to a bug in either RestSharp or MailChimp API. Has anyone had a similar problem?
After several hours we finally found what was causing this..
When RestSharp is making the request to https://us2.api.mailchimp.com/3.0/ it's opting to omit the trailing '/'
(even if you specifically add this in the RestRequest, like: new RestRequest("/", Method.GET))
so the request was made to https://us2.api.mailchimp.com/3.0
This caused a serverside redirect to 'https://us2.api.mailchimp.com/3.0/' (with the trailing '/') and for some reason this redirect scrubbed away the authentication header.
So we tried making a
new RestRequest("/", Method.GET)
with some parameters (req.AddParameter("fields", "email")) to make it not scrub the trailing '/', but this to was failing.
The only way we were able to "fool" RestSharp was to write it a bit less sexy like:
new RestRequest("/?fields=email", Method.GET)

ASP.NET authorization using RestSharp

On the site "example.net" I have standart api method to take access token (which i can call /Token) and if I make POST request using Fiddler to example.net/Token with parameters in request body
And all is OK. Status code 200 and in the response access token and other info.
But if I do this request from other site using RestSharp - 500 Internal Server Error. I tried to AddParameter, AddBody, AddObject. Make parameters as a JSON string, to change DataFormat, to AddHeader of Content-Type. This is my last version of request.
request = new RestRequest(URL, Method.POST);
//request.AddHeader("Content-Type", ContentType);
string UrlEncoded = "";
//I parse Parameters to format like I use in request body in Fiddler.
if (Parameters.Count != 0)
foreach (var param in Parameters)
UrlEncoded = param.ParamToUrlEncoded(UrlEncoded);
request.AddBody(UrlEncoded);
IRestResponse response = client.Execute(request);
var content = response.Content;
Do i need to set any more attributes on the request or something?
Thank you.

Adding product to google shopping. (400) Bad Request

I am getting frustrated with this error.
I am using the .NET Client library to connect and to post products to google shopping.
I keep getting this error (I have replaced the correct Id with x's):
The remote server returned an error: (400) Bad Request.
[GDataRequestException: Execution of request failed: https://content.googleapis.com/content/v1/xxxxxx/items/products/schema]
Google.GData.Client.GDataRequest.Execute() +159
In my code I am doing it like this after successfull authentication:
string serviceName = "structuredcontent";
string userAgent = "content-api-example";
GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(serviceName, userAgent, _parameters);
_service = new ContentForShoppingService(userAgent, accountId);
_service.RequestFactory = requestFactory;
ProductEntry productEntry = _service.Insert(entry);
Can anyone see what is wrong?

How to Pass parameters in SOAP request in wp7

I have done with the simple SOAP parsing in wp7 with adding reference of SOAP Service in my application.
but i don't understand how to pass parameters in soap request ?
my SOAP Service is this
http://www.manarws.org/ws/manarService.asmx?op=fnGetSubCertificate
with the Certificate id is : 8
i have search about this last 5 days but don't get any way to do this.
Please help me.
After adding the service reference for your project, as I explained in the previous SO post:
You can make the web request like this and pass the parameters.
manarServiceSoapClient client = new manarServiceSoapClient();
client.fnGetSubCertificateCompleted += client_fnGetSubCertificateCompleted;
client.fnGetSubCertificateAsync("8");
And the response is obtained in the Completed handler
void client_fnGetSubCertificateCompleted(object sender, fnGetSubCertificateCompletedEventArgs e)
{
var resp = e.Result;
}
I got response like this
[{"ArTitle":"مركز السمع والكلام ","EnTitle":"Hearing & Speech Center ","PhotosCatsId ...
//Removed the rest

Resources