Condividi tramite


ServiceClient Class

Definition

Primary implementation of the API interface for Dataverse.

public class ServiceClient : IDisposable, Microsoft.PowerPlatform.Dataverse.Client.IOrganizationServiceAsync2, Microsoft.Xrm.Sdk.IOrganizationService
type ServiceClient = class
    interface IOrganizationService
    interface IOrganizationServiceAsync2
    interface IOrganizationServiceAsync
    interface IDisposable
Public Class ServiceClient
Implements IDisposable, IOrganizationService, IOrganizationServiceAsync2
Inheritance
ServiceClient
Implements

Remarks

Uses Microsoft Authentication Library (MSAL) for authentication.

Constructors

ServiceClient(ConnectionOptions, Boolean, ConfigurationOptions)

Creating the ServiceClient Connection with a ConnectionOptions Object and ConfigurationOptions Object. This allows for deferred create of a Dataverse Service Client.

ServiceClient(String, ILogger)

ServiceClient to accept the connectionstring as a parameter

ServiceClient(String, SecureString, String, String, Boolean, OrganizationDetail, String, Uri, PromptBehavior, Boolean, String, ILogger)

Log in with OAuth for online connections,

Utilizes the discovery system to resolve the correct endpoint to use given the provided server orgName, user name and password.

ServiceClient(String, SecureString, String, String, String, String, Boolean, Boolean, OrganizationDetail, String, Uri, PromptBehavior, String, ILogger)

Log in with OAuth for On-Premises connections.

ServiceClient(String, SecureString, Uri, Boolean, String, Uri, PromptBehavior, Boolean, String, ILogger)

Log in with OAuth for online connections,

Will attempt to connect directly to the URL provided for the API endpoint.

ServiceClient(Uri, Func<String,Task<String>>, Boolean, ILogger)

Creates an instance of ServiceClient who's authentication is managed by the caller. This requires the caller to implement a function that will accept the InstanceURI as a string will return the access token as a string on demand when the ServiceClient requires it. This approach is recommended when working with WebApplications or applications that are required to implement an on Behalf of flow for user authentication.

ServiceClient(Uri, String, SecureString, Boolean, ILogger)

ClientID \ ClientSecret Based Authentication flow, allowing for Secure Client ID passing.

ServiceClient(Uri, String, String, Boolean, ILogger)

ClientID \ ClientSecret Based Authentication flow.

ServiceClient(X509Certificate2, StoreName, String, Uri, Boolean, OrganizationDetail, String, Uri, ILogger)

Log in with Certificate Auth OnLine connections. This requires the org API URI.

ServiceClient(X509Certificate2, StoreName, String, Uri, String, Boolean, Boolean, OrganizationDetail, String, Uri, ILogger)

Log in with Certificate Auth On-Premises connections.

Fields

_sdkVersionProperty

SDK Version property backer.

Properties

ActiveAuthenticationType

Authentication Type to use

Authority

OAuth Authority.

CallerAADObjectId

Gets or Sets the AAD Object ID of the caller. This is supported for Xrm 8.1 + only

CallerId

Gets or Sets the current caller ID

ConnectedOrgFriendlyName

Returns the friendly name of the connected Dataverse instance.

ConnectedOrgId

ID of the connected organization.

ConnectedOrgPublishedEndpoints

Returns the endpoint collection for the connected org.

ConnectedOrgUniqueName

Returns the unique name for the org that has been connected.

ConnectedOrgUriActual

Returns the Actual URI used to connect to Dataverse. this URI could be influenced by user defined variables.

ConnectedOrgVersion

Returns the Version Number of the connected Dataverse organization. If access before the Organization is connected, value returned will be null or 0.0

CurrentAccessToken

Returns the current access token in Use to connect to Dataverse. Note: this is only available when a token based authentication process is in use.

DisableCrossThreadSafeties

Disabled internal cross thread safeties, this will gain much higher performance, however it places the requirements of thread safety on you, the developer.

EnableAffinityCookie

Defaults to True.

When true, this setting applies the default connection routing strategy to connections to Dataverse.

This will 'prefer' a given node when interacting with Dataverse which improves overall connection performance.

When set to false, each call to Dataverse will be routed to any given node supporting your organization.

See Server affinity for proper use.

EnvironmentId

Gets the PowerPlatform Environment Id of the environment that is hosting this instance of Dataverse

ForceServerMetadataCacheConsistency

This will force the Dataverse server to refresh the current metadata cache with current DB config. Note, that this is a performance impacting property. Use of this flag will slow down operations server side as the server is required to check for consistency of the platform metadata against disk on each API call executed. It is recommended to use this ONLY in conjunction with solution import or delete operations.

InMemoryLogCollectionEnabled

Enabled Log Capture in memory This capability enables logs that would normally be sent to your configured

InMemoryLogCollectionTimeOutMinutes

This is the number of minuets that logs will be retained before being purged from memory. Default is 5 min. This capability controls how long the log cache is kept in memory.

IsBatchOperationsAvailable

if true then Batch Operations are available.

IsReady

if true the service is ready to accept requests.

LastError

Returns the Last String Error that was created by the Dataverse Connection

LastException

Returns the Last Exception from Dataverse.

MaxConnectionTimeout

Gets or sets the maximum timeout for the connection.

MaxRetryCount

Gets or sets max retry count.

OAuthUserId

Logged in Office365 UserId using OAuth.

OrganizationDetail

OrganizationDetails for the currently connected environment.

RecommendedDegreesOfParallelism

Server Hint for the number of concurrent threads that would provide optimal processing.

RetryPauseTime

Gets or sets retry pause time.

SdkVersionProperty

Get the Client SDK version property

SessionTrackingId

This ID is used to support Dataverse Telemetry when trouble shooting SDK based errors. When Set by the caller, all Dataverse API Actions executed by this client will be tracked under a single session id for later troubleshooting. For example, you are able to group all actions in a given run of your client ( several creates / reads and such ) under a given tracking id that is shared on all requests. providing this ID when reporting a problem will aid in trouble shooting your issue.

TenantId

Gets the Tenant Id of the current connection.

UseWebApi

Use Dataverse Web API instead of Dataverse Object Model service where possible - Defaults to False.

Methods

Associate(String, Guid, Relationship, EntityReferenceCollection)

Issues an Associate Request to Dataverse.

AssociateAsync(String, Guid, Relationship, EntityReferenceCollection)

Associate an entity with a set of entities

AssociateAsync(String, Guid, Relationship, EntityReferenceCollection, CancellationToken)

Associate an entity with a set of entities

Clone(Assembly, ILogger)

Clone, 'Clones" the current Dataverse Service client with a new connection to Dataverse. Clone only works for connections creating using OAuth Protocol.

Clone(ILogger)

Clone, 'Clones" the current Dataverse ServiceClient with a new connection to Dataverse. Clone only works for connections creating using OAuth Protocol.

Connect()

Connects the Dataverse Service Client instance when staged with the Deferd Connection constructor.

Create(Entity)

Issues a Create request to Dataverse

CreateAndReturnAsync(Entity)

Create an entity and process any related entities

CreateAndReturnAsync(Entity, CancellationToken)

Create an entity and process any related entities

CreateAsync(Entity)

Create an entity and process any related entities

CreateAsync(Entity, CancellationToken)

Create an entity and process any related entities

CreateRequestBuilder()
Delete(String, Guid)

Issues a Delete request to Dataverse

DeleteAsync(String, Guid)

Delete instance of an entity

DeleteAsync(String, Guid, CancellationToken)

Delete instance of an entity

Disassociate(String, Guid, Relationship, EntityReferenceCollection)

Issues a Disassociate Request to Dataverse.

DisassociateAsync(String, Guid, Relationship, EntityReferenceCollection)

Disassociate an entity with a set of entities

DisassociateAsync(String, Guid, Relationship, EntityReferenceCollection, CancellationToken)

Disassociate an entity with a set of entities

DiscoverOnlineOrganizationsAsync(Func<String,Task<String>>, Uri, String, ILogger)

Discovers Organizations Using the global discovery service and an external source for access tokens

DiscoverOnlineOrganizationsAsync(Func<String,Task<String>>, Uri, String, ILogger, CancellationToken)
DiscoverOnlineOrganizationsAsync(String, String, String, Uri, Boolean, String, PromptBehavior, Boolean, DiscoveryServer, String, ILogger)

Discovers Organizations Using the global discovery service.

Provides a User ID / Password flow for authentication to the online discovery system. You can also provide the discovery instance you wish to use, or not pass it. If you do not specify a discovery region, the commercial global region is used

DiscoverOnlineOrganizationsAsync(Uri, ClientCredentials, String, Uri, Boolean, String, PromptBehavior, Boolean, String, ILogger)

Discovers the organizations, used for OAuth.

DiscoverOnPremiseOrganizationsAsync(Uri, ClientCredentials, String, Uri, String, PromptBehavior, Boolean, String, ILogger)

Discovers the organizations against an On-Premises deployment.

Dispose()

Disposed the resources used by the ServiceClient.

Execute(OrganizationRequest)

Executes a general organization request

ExecuteAsync(OrganizationRequest)

Perform an action in an organization specified by the request.

ExecuteAsync(OrganizationRequest, CancellationToken)

Perform an action in an organization specified by the request.

ExecuteOrganizationRequest(OrganizationRequest, String, Boolean)

Executes a Dataverse Organization Request (thread safe) and returns the organization response object. Also adds metrics for logging support.

ExecuteOrganizationRequestAsync(OrganizationRequest, String, Boolean, CancellationToken)

Executes a Dataverse Organization Request (In Async mode) and returns the organization response object. Also adds metrics for logging support.

ExecuteWebRequest(HttpMethod, String, String, Dictionary<String,List<String>>, String, CancellationToken)

Executes a web request against the Dataverse Web API.

ExecuteWebRequestAsync(HttpMethod, String, String, Dictionary<String,List<String>>, String, CancellationToken)

Executes an asychronous web request against the Dataverse Web API.

GetAllLogs()

Enabled only if InMemoryLogCollectionEnabled is true. Return all logs currently stored for the ServiceClient in queue.

GetAllLogsAsStringList()

Enabled only if InMemoryLogCollectionEnabled is true. Return all logs currently stored for the ServiceClient in queue in string list format with [UTCDateTime][LogEntry].

MakeSecureString(String)

Makes a secure string

RemoveOAuthTokenCache(String)

Clear the persistent and in-memory store cache

Retrieve(String, Guid, ColumnSet)

Issues a Retrieve Request to Dataverse

RetrieveAsync(String, Guid, ColumnSet)

Retrieves instance of an entity

RetrieveAsync(String, Guid, ColumnSet, CancellationToken)

Retrieves instance of an entity

RetrieveMultiple(QueryBase)

Issues a RetrieveMultiple Request to Dataverse

RetrieveMultipleAsync(QueryBase)

Retrieves a collection of entities

RetrieveMultipleAsync(QueryBase, CancellationToken)

Retrieves a collection of entities

Update(Entity)

Issues an update to Dataverse.

UpdateAsync(Entity)

Updates an entity and process any related entities

UpdateAsync(Entity, CancellationToken)

Updates an entity and process any related entities

Extension Methods

CreateBatchOperationRequest(ServiceClient, String, Boolean, Boolean)

Create a Batch Request for executing batch operations. This returns an ID that will be used to identify a request as a batch request vs a "normal" request.

ExecuteBatch(ServiceClient, Guid)

Begins running the Batch command.

GetBatchById(ServiceClient, Guid)

Returns a request batch by BatchID

GetBatchOperationIdRequestByName(ServiceClient, String)

Returns the batch id for a given batch name.

GetBatchRequestAtPosition(ServiceClient, Guid, Int32)

Returns the organization request at a give position

ReleaseBatchInfoById(ServiceClient, Guid)

Release a batch from the stack Once you have completed using a batch, you must release it from the system.

RetrieveBatchResponse(ServiceClient, Guid)

Executes the batch command and then parses the retrieved items into a list. If there exists a exception then the LastException would be filled with the first item that has the exception.

CloseActivity(ServiceClient, String, Guid, String, String, Guid, Boolean)

Closes the Activity type specified. The Activity Entity type supports fax , letter , and phonecall

*Note: This will default to using English names for Status. if you need to use Non-English, you should populate the names for completed for the status and state.

CreateAnnotation(ServiceClient, String, Guid, Dictionary<String,DataverseDataTypeWrapper>, Guid, Boolean)

This creates a annotation [note] entry, related to a an existing entity

Required Properties in the fieldList

notetext (string) = Text of the note,

subject (string) = this is the title of the note

CreateEntityAssociation(ServiceClient, String, Guid, String, Guid, String, Guid, Boolean)

Associates one Entity to another where an M2M Relationship Exists.

CreateMultiEntityAssociation(ServiceClient, String, Guid, String, List<Guid>, String, Guid, Boolean, Boolean)

Associates multiple entities of the same time to a single entity

CreateNewActivityEntry(ServiceClient, String, String, Guid, String, String, String, Dictionary<String,DataverseDataTypeWrapper>, Guid, Boolean)

Creates a new activity against the target entity type

CreateNewRecord(ServiceClient, String, Dictionary<String,DataverseDataTypeWrapper>, String, Boolean, Guid, Boolean)

Uses the dynamic entity patter to create a new entity

DeleteEntity(ServiceClient, String, Guid, Guid, Boolean)

Deletes an entity from the Dataverse

DeleteEntityAssociation(ServiceClient, String, Guid, String, Guid, String, Guid, Boolean)

Removes the Association between 2 entity items where an M2M Relationship Exists.

UpdateEntity(ServiceClient, String, String, Guid, Dictionary<String,DataverseDataTypeWrapper>, String, Boolean, Guid, Boolean)

Generic update entity

UpdateStateAndStatusForEntity(ServiceClient, String, Guid, Int32, Int32, Guid, Boolean)

Updates the State and Status of the Entity passed in.

UpdateStateAndStatusForEntity(ServiceClient, String, Guid, String, String, Guid, Boolean)

Updates the State and Status of the Entity passed in.

DeleteAndPromoteSolutionAsync(ServiceClient, String)

Executes a Delete and Propmote Request against Dataverse using the Async Pattern.

GetAsyncOperationStatus(ServiceClient, Guid)
ImportDataMap(ServiceClient, String, Boolean, Boolean)

Used to upload a data map to the Dataverse

ImportSolution(ServiceClient, Guid, Guid, Boolean, Boolean, Boolean, Boolean, Boolean, Dictionary<String,Object>)
ImportSolution(ServiceClient, String, Guid, Boolean, Boolean, Boolean, Boolean, Boolean, Dictionary<String,Object>)

Imports a Dataverse solution to the Dataverse Server currently connected.

*** Note: this is a blocking call and will take time to Import to Dataverse ***

ImportSolutionAsync(ServiceClient, Guid, Guid, Boolean, Boolean, Boolean, Boolean, Boolean, Dictionary<String,Object>)
ImportSolutionAsync(ServiceClient, String, Guid, Boolean, Boolean, Boolean, Boolean, Boolean, Dictionary<String,Object>)

Import Solution Async used Execute Async pattern to run a solution import.

InstallSampleData(ServiceClient)

Request Dataverse to install sample data shipped with Dataverse. Note this is process will take a few moments to execute.

This method will return once the request has been submitted.

IsSampleDataInstalled(ServiceClient)

Determines if the Dataverse sample data has been installed

RetrieveSolutionImportResultAsync(ServiceClient, Guid, Boolean)
StageSolution(ServiceClient, String, MemoryStream)
SubmitImportRequest(ServiceClient, DeploymentExtensions+ImportRequest, DateTime)

Starts an Import request for CDS.

Supports a single file per Import request.

UninstallSampleData(ServiceClient)

Request Dataverse to remove sample data shipped with Dataverse. Note this is process will take a few moments to execute. This method will return once the request has been submitted.

AddEntityToQueue(ServiceClient, Guid, String, String, Guid, Boolean, Guid, Boolean)

This will route a Entity to a public queue,

AssignEntityToUser(ServiceClient, Guid, String, Guid, Guid, Boolean)

Assign an Entity to the specified user ID

ExecuteWorkflowOnEntity(ServiceClient, String, Guid, Guid, Boolean)

Executes a named workflow on an object.

GetMyUserId(ServiceClient)

Returns the user ID of the currently logged in user.

SendSingleEmail(ServiceClient, Guid, String, Guid, Boolean)

this will send an Email to the

CreateOrUpdatePickListElement(ServiceClient, String, String, List<LocalizedLabel>, Int32, Boolean)

Adds an option to a pick list on an entity.

GetAllAttributesForEntity(ServiceClient, String)

Returns all attributes on a entity

GetAllEntityMetadata(ServiceClient, Boolean, EntityFilters)

Returns a list of entities with basic data from Dataverse

GetEntityAttributeMetadataForAttribute(ServiceClient, String, String)

Gets metadata for a specific entity's attribute.

GetEntityDisplayName(ServiceClient, String, Int32)

Gets an Entity Name by Logical name or Type code.

GetEntityDisplayNamePlural(ServiceClient, String, Int32)

Gets an Entity Name by Logical name or Type code.

GetEntityFormIdListByType(ServiceClient, String, FormTypeId)

Returns the Form Entity References for a given form type.

GetEntityMetadata(ServiceClient, String, EntityFilters)

Returns the Metadata for an entity from Dataverse, defaults to basic data only.

GetEntityName(ServiceClient, Int32)

Returns the Entity name for the given Type code

GetEntityTypeCode(ServiceClient, String)

Gets the typecode of an entity by name.

GetGlobalOptionSetMetadata(ServiceClient, String)

Gets a global option set from Dataverse.

GetPickListElementFromMetadataEntity(ServiceClient, String, String)

Gets a PickList, Status List or StateList from the metadata of an attribute

PublishEntity(ServiceClient, String)

Publishes an entity to the production system, used in conjunction with the Metadata services.

ResetLocalMetadataCache(ServiceClient, String)

This will clear the Metadata cache for either all entities or the specified entity

GetActivitiesBy(ServiceClient, String, Guid, List<String>, LogicalSearchOperator, Dictionary<String,String>, Dictionary<String,LogicalSortOrder>, Int32, Int32, String, String, Boolean, Guid)

Returns all Activities Related to a given Entity ID. Only Account, Contact and Opportunity entities are supported.

GetActivitiesBy(ServiceClient, String, Guid, List<String>, LogicalSearchOperator, List<DataverseSearchFilter>, Dictionary<String,LogicalSortOrder>, Int32, Int32, String, String, Boolean, Guid)

Returns all Activities Related to a given Entity ID. Only Account, Contact and Opportunity entities are supported.

GetDataByKeyFromResultsSet<T>(ServiceClient, Dictionary<String,Object>, String)

This function gets data from a Dictionary object, where "string" identifies the field name, and Object contains the data, this method then attempts to cast the result to the Type requested, if it cannot be cast an empty object is returned.

GetEntityDataByFetchSearch(ServiceClient, String, Guid, Boolean)

Searches for data based on a FetchXML query

GetEntityDataByFetchSearch(ServiceClient, String, Int32, Int32, String, String, Boolean, Guid, Boolean)

Searches for data based on a FetchXML query

GetEntityDataByFetchSearchEC(ServiceClient, String, Guid, Boolean)

Searches for data based on a FetchXML query

GetEntityDataByFetchSearchEC(ServiceClient, String, Int32, Int32, String, String, Boolean, Guid, Boolean)

Searches for data based on a FetchXML query

GetEntityDataById(ServiceClient, String, Guid, List<String>, Guid, Boolean)

Gets a List of variables from the account based on the list of field specified in the Fields List

GetEntityDataByLinkedSearch(ServiceClient, String, Dictionary<String, String>, String, Dictionary<String,String>, String, String, String, LogicalSearchOperator, List<String>, Guid, Boolean)

Queries an Object via a M to M Link

GetEntityDataByLinkedSearch(ServiceClient, String, List<DataverseSearchFilter>, String, List<DataverseSearchFilter>, String, String, String, LogicalSearchOperator, List<String>, Guid, Boolean, Boolean)

Queries an Object via a M to M Link

GetEntityDataByRollup(ServiceClient, String, Guid, String, List<String>, LogicalSearchOperator, Dictionary<String,String>, Dictionary<String, LogicalSortOrder>, Guid)

Returns all Activities Related to a given Entity ID. Only Account, Contact and Opportunity entities are supported.

GetEntityDataByRollup(ServiceClient, String, Guid, String, List<String>, LogicalSearchOperator, List<DataverseSearchFilter>, Dictionary<String, LogicalSortOrder>, Int32, Int32, String, String, Boolean, Guid, Boolean)

Returns all Activities Related to a given Entity ID. Only Account, Contact and Opportunity entities are supported.

GetEntityDataBySearchParams(ServiceClient, String, Dictionary<String,String>, LogicalSearchOperator, List<String>, Guid, Boolean)

Gets a list of accounts based on the search parameters.

GetEntityDataBySearchParams(ServiceClient, String, List<DataverseSearchFilter>, LogicalSearchOperator, List<String>, Dictionary<String,LogicalSortOrder>, Int32, Int32, String, String, Boolean, Guid, Boolean)

Searches for data from an entity based on the search parameters.

GetEntityDataBySearchParams(ServiceClient, String, List<DataverseSearchFilter>, LogicalSearchOperator, List<String>, Guid, Boolean)

Gets a list of accounts based on the search parameters.

Applies to