class MSDynamics

Public: Various methods for accessing MS Dynamics.

Public Class Methods

new(config={ hostname: nil, access_token: nil, refresh_token: nil, client_id: nil, client_secret: nil}) click to toggle source

Public: Initialize a MS Dynamics client instance.

config - A configuration object.

# File lib/msdynamics.rb, line 12
def initialize(config={
    hostname: nil, access_token: nil, refresh_token: nil,
    client_id: nil, client_secret: nil})
  # Validate the input.
  if config[:hostname].nil?  && config[:access_token].nil?
    raise RuntimeError.new("hostname and access_token are required")
  end
  # Set up the variables
  @access_token = config[:access_token]
  @refresh_token = config[:refresh_token]
  @hostname = config[:hostname]
  @client_id = config[:client_id]
  @client_secret = config[:client_secret]
  @endpoint = "#{@hostname}/api/data/v8.0/"
  # Get the authenticated user's information ('WhoAmI')
  # This also validates the access tokens and client secrets.
  # If validation fails, it will raise an exception back to the calling app.
  response = DynamicsHTTPClient.request("#{@endpoint}WhoAmI", @access_token)
  @user_id = JSON.parse(response.body)['UserId']
end

Public Instance Methods

get_entity_records(entity_name="") click to toggle source

Public: Gets all the records for a given MS Dynamics entity.

entity_name - ‘accounts’, ‘leads’, ‘opportunities’ or ‘contacts’.

Examples

get_entity_records('accounts')
# => [
       {
         "@odata.etag": "W/\"640532\"",
         "name": "A. Datum",
         "emailaddress1": "vlauriant@adatum.com",
         "telephone1": "+86-23-4444-0100",
         "int_twitter": null,
         "int_facebook": null,
         "accountid": "475b158c-541c-e511-80d3-3863bb347ba8"
       }
     ]

Returns an object with all records for the given entity.

# File lib/msdynamics.rb, line 53
def get_entity_records(entity_name="")
  # Add a filter so we only get records that belong to the authenticated user.
  filter = "_ownerid_value eq (#{@user_id})"
  request_url = "#{@endpoint}#{entity_name}?$filter=#{filter}"
  # Return the array of records
  response = DynamicsHTTPClient.request(request_url, @access_token)
  Hashie::Mash.new(JSON.parse(response.body)).value
end
refresh_token() click to toggle source
# File lib/msdynamics.rb, line 62
def refresh_token()
  response = DynamicsHTTPClient.refresh_token(
    "https://login.windows.net/common/oauth2/token", @refresh_token,
    @client_id, @client_secret, @hostname)
  token_object = Hashie::Mash.new(JSON.parse(response.body))
  @access_token = token_object.access_token
  @refresh_token = token_object.refresh_token
  token_object
end