New work, new life, new blogpost.

Well.. as expected, my plan for once a week went south.
But I finally had something to write about, so here goes.

I was recently tasked with writing a integration for SalesForce at work
Just as any normal task I started with google, what had people done before and was it already solved.
Turns out SalesForce, atlhough it has a really well documented API, does not seem to have a powershell module.

Well, read on to see how awesome it turned out.

First of, i needed a test Salesforce account and settings. Fairly easy, and summarized here:

Data Creation and gathering

  • Create developer account, they are free from here: Salesforce developer account
  • Log in to account webpage
    Note the first letters in the url, https://eu12.lightning.force.com/ eu12 in my case. You’ll need those later.
  • Go to Apps -> App Manager and create a new connected app.
    Note the Consumer key and the consumer secret

    • If you missed them, they can be found in Apps -> connected apps -> manage connected apps
  • Click the small button besides your created app and select ‘View’
    Go to Apps -> Connected Apps -> Manage Connected app -> Click to select your newly created app

    • Check settings for oauth policies. If they are wrong, click edit policies and change
  • Click your user avatar -> settings to go to user settings
  • Select ‘Reset my security token’ to receive user token

You should now have the following infomation:

  • Username (my.user@domain.com)
  • Password (password)
  • Consumer Secret (1234567890123456789)
  • Consumer Key (ReallyLongStringFullOfNumbersLike1234567890AndEvenSomeCharacterrsLike_./ThrownInThere)
  • User Token (25RandomCharactersNumbers)
  • Domain for connection (eu01)

Powershell stuff
Connecting to Salesforce using Oauth password
For all of SalesForce API requests, we need to make sure we use TLS 1.2, but this is not default in Powershell.
To set the security protocol to TLS1.2

> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

In order to send requests to your SalesForce API you first need to get an access token.
You get this by creating a custom webrequest to the oauth endpoint.
Create a body that looks like this:

$authBody = @{
  grant_type = 'password' # This is a string, not your password, to tell the API we want to use Password authentication.
  client_id = $SalesForceClientID # This is your consumer key previously fetched
  client_secret = $SalesForceClientSecret # This is your consumer secret
  username = $SalesForceUsername # Your username
  password = $PassToken # This is a combination of your password and your token. See below.
}

$PassToken is your password and your user token combined in to one string without spaces. In my example above:

> $Password = 'password'
> $UserToken = '25RandomCharactersNumbers'

PassToken would then be ‘password25RandomCharactersNumbers’

> $PassToken = "$SalesForceServicePassword$SalesForceToken"

Now, remember those first letters in your url at the top? eu12?
You need those to know which host you should talk to.
To receive your token, send a POST request with your body to the URI

> https://<yourdomain>.salesforce.com/services/oauth2/token

In my case, it would be

> https://eu12.salesforce.com/services/oauth2/token

If you are successfull, you should now get back something like this:

> access_token :
> instance_url :
> id :
> token_type : 'Bearer' # This is not user specific. For Oauth it is always bearer.
> issued_at :
> signature :

It is good to keep this one in a variable, since we need it for all requests in this session.

> $AccessToken = Invoke-RestMethod -Uri 'https://eu12.salesforce.com/services/oauth2/token' -Method POST -Body $authBody

Now on to the good stuff.

Sending requests to the SalesForce API
We will start of with something somewhat simple right?
Searching for a user!

SalesForce API is actually quite a mess of different endpoints, and not always easy to navigate.
Fortunately, there is a API browser available online, at https://workbench.developerforce.com/
Log in there using your SalesForce account, and select ‘Utilities’ -> ‘Rest Explorer’ to get to the API browser.
Executing the default ‘Get’ will give us a long list of objects to browse,
One of them is ‘Search’.
Clicking that will however only show an error, as we need to input a query of some kind.

Instead of telling you how i know, lets just say i do know that SalesForce uses something called SOQL, Salesforce Object Query Language.
Read all about that here.
Using this link, and also this
We can now start to construct our query. (Yes, in my case that actually included reading loads of more pages. If you are serious about learning SOQL, you should do it to.)
In the end i get something like this:
FIND+{<search>}+IN+<property>+FIELDS+RETURNING+USER(<userproperties>)
Userproperties? Well, back to the workbench explorer.
Users, and a lot of other things, in Salesforce are called SObjects.
Entering the SObjects API we find a User, and under that a Describe. Describing users sounds good.
This endpoint contains a fields ‘folder’ showing the available properties,
And using this information we can now nomplete the query:

FIND+{björn}+IN+name+FIELDS+RETURNING+USER(id,name,username)

So using the error from the /search url, we can construct a full query URL

/services/data/v41.0/search/?q=FIND+{björn}+IN+name+FIELDS+RETURNING+USER(id,name,username)

Paste it into the Workbench field and execute. Success!
But we are not here to browse stuff.

Using the $accessToken we have, we can create a complete search request.

> $Method = 'Get' # What was set in the workbench
> $URI = "$($AccessToken.instance_url)/services/data/v41.0/search/?q=FIND+{björn}+IN+name+FIELDS+RETURNING+USER(id,name,username)" # The URL from your token plus the relative path from workbench
> $Headers = @{
  'Authorization' = "Bearer $($AccessToken.access_token)"
  'Accept' = 'application/json'
} # See description below

We must alwas set the header in our requests, as that is how we show that we have the correct token.
Using Oauth username password it is always set as the string ‘Bearer access_token’
Also, we always want json offcourse 😉

So lets try it:

> Invoke-RestMethod -URI $URI -Method $Method -Headers $Headers

Success!

And you can now go ahead and start messing about in the SalesForce API.

But I started by saying it turned out awesome.
Just searching using powershell and variables isn’t that nice,
So I wrapped this, and a few more api calls in a module,
Alongside a ‘Invoke-APSalesForceRestMethod’ that automaticatly wraps the token and creates a valid request from it.

Then we managed to convince our employer to open source it.

So without further delay,
you can download / fork / clone our SalesForce module here:
https://github.com/SnowSoftware/AutomationPlatform-SalesForce.Integration
And please help out, send bug reports, add functionality and use it!

And this is the awesome part.
We managed to get our company, Snow Software, to open source our software.
and there is more to come, so stay tuned!

 

Oh, and I still need to learn how to format things on my blog..

 

‘Til nex time, whenever that may be!

Silence is golden.

I bet you thought this was going to be a different song.

So, I have been of grid for a while now.. time to get going again.
I’ve had my summer vacation,
and decided that now was not the time to be a techie,
so I have not even started my computer once in over a month.
You should try that some time. It feels good.

But there has also been another reason for my silence.
Nervousness. Happiness. Random outbursts of feelings.
Why? Well, I´ll start you off with words from the man himself, @jsnover.
‘I love to hear stories about how people learn PowerShell,
And it makes their career go forward’
(Not exact quote, but he says that a lot).

In three weeks I am joining the ranks at Snow Software,
and it is not without pride I say that my new title is going to be PowerShell Developer.

When I told one of my friends about this, he asked
‘How come you ended up there?
You were supposed to be a musician, right?’
And as I told him the story of my life, Jeffrey’s quote above came to mind.
How did I end up here?
Well, if someone is interested in the full story, ask me.
I love talking about myself.
But I can give you the brief PowerShell history.

(And if you’re already bored, as I would think, go read @joshduffney ‘s post of Pester. Really. It’s good.)

After I finished school I was going to be a rock star.
But as this was the end of the IT boom,
people with computer skills was high in demand,
and I have been an avid computer user since I was six years old,
(You never forget your first C=64).
So I took a job as a hardware tester/builder at a distributor company until my rock star career would take off.

I first installed PowerShell way back.
I don’t even remember when.
But being a CMD scriptkiddie, I didn’t get it.

Until 2009 (2010? might have been..),
when I was tasked with improving a SQL/TFS creation script.
I rewrote it in PowerShell using google copy and paste,
and it was ugly but working.
If I find it, I will redo this post in script format.

Since the word was out that PowerShell was the thing,
I decided to replace my beloved CMD shortcut with a PS one instead,
and forced myself to use that instead,
replacing all my known commands with the PowerShell equivalent.

After a while I started using WMI,
and that was when the light bulb lit up.
I ran head first in to it,
and within a year or so
I had replaced all my CMD scripts with PowerShell instead.

Along came new PowerShell versions,
new tasks, and new discoveries (Remoting and modules in PS2!)

And here I am, almost ten years later.
Pester, DSC, the DevOps movement..
So much fun stuff to learn, use, test!

And with a new job.
As a Powershell Developer.
Until my rock star career takes of that is.