SalesForce.com – Accessing using Web Services and Scripting – Part 3

March 23, 2016

 

Powershell – SalesForce.com – REST Example :

CLS

function Get-AuthorizationTokenWithUsernamePasswordFlow ` 
($client_id, $client_secret, $username, $password, $security_token)
{
    Add-Type -AssemblyName System.Web

    # $uri = "https://test.salesforce.com/services/oauth2/token";
    $uri = "https://login.salesforce.com/services/oauth2/token";
    $grant_type = "password";

    $username = [System.Web.HttpUtility]::UrlEncode($username)
    $password = [System.Web.HttpUtility]::UrlEncode($password)

    $requestBody = "";
    $requestBody += "grant_type=$grant_type";
    $requestBody += "&client_id=$client_id";
    $requestBody += "&client_secret=$client_secret";
    $requestBody += "&username=$username";
    $requestBody += "&password=$password$security_token";

    
    Write-Host "Uri:" $uri
    Write-Host "Body:" $requestBody

    Invoke-RestMethod -Method Post -Uri $uri -Body $requestBody
}

# usage create a ClientID and ClientSecret
# https://help.salesforce.com/apex/HTViewSolution?id=000205876&language=en_US

# https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com
# Obtaining a Token in an Autonomous Client (Username and Password Flow)

$Cred = Get-Credential -credential "Email.Address@Company.com"
$username = $Cred.UserName
$password = $Cred.GetNetworkCredential().Password $client_id = "YOUR CLIENT ID";
$client_secret = "YOUR CLIENT SECRET";
$security_token = "YOUR SECURITY TOKEN";

# Debug
 Get-AuthorizationTokenWithUsernamePasswordFlow ` 
 $client_id $client_secret $username $password $security_token

$Token = Get-AuthorizationTokenWithUsernamePasswordFlow ` 
$client_id $client_secret $username $password $security_token

$URI = $Token.instance_url+"/services/data/v20.0/"

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

Write-Host ""

# Response = availaible REST services

$Response

Write-Host ""

# Query Accounts Example 
Write-Host "Accounts :"

$StrQuery = "SELECT Name, Id from Account LIMIT 100"

$URI = $Token.instance_url+"/services/data/v20.0/query?q=" + $StrQuery

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

Write-Host ""
Write-Host " # of Records : "
$Response.records.Count

Write-Host ""
Write-Host "Enum Account Name :"
$Response.records | % {$_.name}


# Query Opporunities Example 
$StrQuery = "SELECT AccountId, OwnerId, Name, Description, ` 
StageName, Amount, Probability FROM Opportunity WHERE StageName <> `</pre>
<pre>'Closed Lost' ORDER BY StageName "

$URI = $Token.instance_url+"/services/data/v20.0/query?q=" + $StrQuery

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

$Response.records.Count

Write-Host ""
Write-Host "Query Output :"

Foreach ($objItem in $Response.records) {

    "{0,-120} {1, 25} {2, 30}" -f `
 
   $objItem.name, $objItem.StageName, $objItem.Amount
 }

This script will return your Access Token, using this function

Get-AuthorizationTokenWithUsernamePasswordFlow

image

Next it will list the REST API’s you can use

image

Query Accounts Example :

image

Enjoy !

Smile

Advertisements

PowerShell – Invoke-RestMethod Error !

July 14, 2014

When running the PS Invoke-RestMethod, I got the connection closed Error ?

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.

image

Looking on the net there are a lot’s simular posts coming up, providing solutions that had to do with avoiding certificates validation checks when running the script ?

like adding this to the script :

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = ´
                        New-Object TrustAllCertsPolicy

Or

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

But, none of them worked out well?

So the solution is here :

When specifying an URI for the Invoke-RestMethode, don’t pre-fix it with HTTP:// or HTTPS://

Example :

Invoke-RestMethod -Uri "gdata.youtube.com/feeds/api/videos?v=2&q=PowerShell" `
| Select-Object Title, Author, Link

Result :

image

As simple as that Winking smile


SharePoint – REST Interface, JSON output

July 1, 2014

REST and JSON are hot these days, prior to SOAP and XML.

Luckily for PowerShell scripters, SharePoint has an REST interface.

And PowerShell has a JSON class.

Here is an example on how to combine both.

CLS

$creds = Get-Credential # get and save credentials

$url = "http://YourSite/_vti_bin/listdata.svc/YourList"

# Once you have the URI set,
# you can use the Invoke-RestMethod cmdlet to get the required information back:
# -UseDefaultCredentials or -Credential $cred

$ListService = Invoke-RestMethod -Uri $URL -Credential $cred

echo $ListService | select ID, Name | ConvertTo-Json

If you have more examples let’s please share.