cub-e.net

just coding...

Improve Microsoft Dynamics 365/CRM service channel allocation performance

The OrganizationServiceProxy and DiscoveryServiceProxy service proxy classes provide the ability to establish a connection to and communicate with the available Microsoft Dynamics 365/CRM services. However, improper use of these API's can potentially reduce application performance. Therefore, if you understand when and how to effectively leverage these service client API's, available in the SDK, you can optimize communication traffic between your application the Dynamics 365/CRM server.

 

When you establish a Windows Communication Foundation (WCF) service channel by using one of the service endpoints, for example, the Organization.svc, your application must perform two additional, time-consuming operations: 1) metadata download from the endpoint and 2) user authentication. You can improve performance if your application performs these operations a minimum number of times for each application session. The OrganizationServiceProxy constructor shown below performs both of these operations, in addition to allocating a new service channel, every time a service proxy object is created.

 

Violation Example

new OrganizationServiceProxy(new Uri(this.orgServiceUrl), nullthis.Credentials, null)

A first step towards improving performance is to minimize the number of times your application uses this constructor to create an instance of the service proxy.  If possible, use this constructor only one time during the application session and cache the returned reference for use in different code paths within your application. Notice that the returned service reference is not thread safe so multi-threaded applications will need to allocate one instance per thread. Applications must also call Dispose on the service proxy object before they terminate in order to free service channel allocated resources.

 

The service proxy class performs the two previously mentioned operations, metadata download and user authentication, by using the following public methods available as client API's.

 

Guideline Example

IServiceManagement<IOrganizationService> sm = ServiceConfigurationFactory

        .CreateManagement<IOrganizationService>(new Uri(orgServiceUrl));

 

this.Credentials = sm.Authenticate(this.Credentials);

 

The CreateManagement method performs the metadata download while the Authenticate method authenticates the user. The returned objects from these methods are thread safe and can be statically cached by your application. 

 

As a more efficient alterntive, you can then use these objects to construct a service proxy object via one of the other constructor overloads (depending on the authentication scenario):

 

newOrganizationServiceProxy(sm, this.Credentials.ClientCredentials)

 

newOrganizationServiceProxy(sm, this.Credentials.SecurityTokenResponse)

These constructor overloads bypass the two aforementioned operations and use the referenced service management and authentication credentials passed as method arguments.  By caching the service management and authenticated credential objects, your application can more efficiently construct the service proxy objects and allocate multiple service channels as necessary over the lifetime of an application session without repeating the costly (and redundant) operations. 

 

If you enable early-bound types on OrganizationServiceProxy through one of the EnableProxyTypes methods, you must do the same on all service proxies that are created from the cached IServiceManagement object. If your application uses the metadata, we recommend that it caches the metadata that it retrieves and periodically calls the RetrieveTimestampRequest message to determine whether it must refresh the cache.

 

In addition, monitor your WCF security token (Token) and refresh it before it expires so that you do not lose the token and have to start over with authentication. To check the token, create a custom class that inherits from the OrganizationServiceProxy or DiscoveryServiceProxy class and that implements the business logic to check the token. Or wrap the proxy classes in a new class. Another technique is to explicitly check the token before each call to the web service. Example code that demonstrates these techniques can be found in the ManagedTokenDiscoveryServiceProxy, ManagedTokenOrganizationServiceProxy, and AutoRefreshSecurityToken classes in the Helper Code: ServerConnection Class topic.

 


Performance Best-Practices: 

http://msdn.microsoft.com/en-us/library/gg509027.aspx#Performance

ServiceConfigurationFactory.CreateManagement<TService>(Uri serviceUri)

http://msdn.microsoft.com/en-us/library/hh560440.aspx

IServiceManagement.Authenticate(AuthenticationCredentials authenticationCredentials)

http://msdn.microsoft.com/en-us/library/hh560432.aspx

Use Try and Finally on Disposable Resources

Why

Using a try/finally block ensures that resources are disposed even if an exception occurs. Not disposing resources properly leads to performance degradation over time. 

When

This is important guideline when working with disposable resources such as 

  • Database connections 
  • File handles 
  • Message queue handles 
  • Text reader, writer 
  • Binary reader, writer 
  • Crypto stream 
  • Symmetric, Asymmetric and Hash algorithms. 
  • Windows Identity, Windows Impersonation Context  
  • Timer, Wait Handle in case of threading 
  • Impersonation Context 
  • XML Reader 
  • XML Writer

How

The following code fragment demonstrates disposing resources in a finally block..

SqlConnection conn = new SqlConnection(...)

try

{

   conn.Open();

   ...

}

finally

{

   if(null != conn)

     conn.close();

}

If developing in C# you can use the 'using' keyword which will automatically dispose resources after their usage.

using(SqlConnection conn = new SqlConnection(...))

{

   conn.Open();   

   ....

}


Problem Example

A database connection is opened and used to access data. 

Unfortunately, if there is an exception other than SqlException or if the exception handling code itself throws an exception the database connection won't be closed. This failure to close database connections could cause the application to run out of database connection impacting application performance.

try

{

   conn.Open();

   // do something with the connection

   // some more processing

   // close the connection

   if(conn != null)

     conn.Close();

}

catch(SqlException ex)

{

   // do exception handling

   // close the connection

   if(conn != null)

     conn.Close();

}

Solution Example

A database connection is opened and used to access data. The finally block will be executed whether there is exception or not, ensuring that the database connection is closed. 

SqlConnection conn = new SqlConnection(...)

try

{

   conn.Open();

   // do something with the connection

   // some more processing

}

catch(SqlException ex)

{

   // do exception handling 

  

}

finally

{

   // close the connection

   if(conn != null)

     conn.Close();

}

 

 

Additional Resources

Related Items

Explicitly Call Dispose or Close on Resources You Open

If you use objects that implement the IDisposable interface, make sure you call the Dispose method of the object or the Close method if one is provided. Database connection and files are examples of shared resources that should be explicitly closed. 


Why

Failing to call Close or Dispose prolongs the life of the object in memory long after the client stops using it. This defers the cleanup and will result in inefficient memory usage. 

When

This guideline should be used when working with disposable resources such as:

  • Database connections 
  • File handles 
  • Message queue handles 
  • Text reader, writer 
  • Binary reader, writer 
  • Crypto stream 
  • Symmetric, Asymmetric and Hash algorithms. 
  • Windows Identity, Windows Impersonation Context  
  • Timer, Wait Handle in case of threading 
  • Impersonation Context 
  • XML Reader 
  • XML Writer 

How

When working with disposable resources call Dispose method of the object or Close method, if provided. The Close method internally calls the dispose method. The finally clause of the try/finally block is a good place to ensure that the Close or Dispose method of the object is called.

The following Visual Basic® .NET code fragment demonstrates disposing resources in finally block.

Try

  conn.Open()

…Finally

  If Not(conn Is Nothing) Then

    conn.Close()

  End If

End Try

In Visual C#®, you can wrap resources that should be disposed, by using a using block. When the using block completes, Dispose is called on the object listed in the brackets on the using statement. The following code fragment shows how you can wrap resources that should be disposed by using a using block.

using (SqlConnection conn = new SqlConnection(connString))

{

  conn.Open();

  . . .

} // Dispose is automatically called on the connection object conn here.


Problem Example

A .NET application opens a database connection. Unfortunately, the database connection is never disposed. Since it is not explicitly disposed the connection will stay active until the application terminates.  This unnecessarily increases the application's memory usage. Database connections are a limited resource, failure to dispose could result in the usage of all available database connections.

SqlConnection conn = new SqlConnection(...)

try

{

   conn.Open();

   // do some processing with the connection

}

catch(SqlException ex)

{

   // do exception handling

}


Solution Example

A .NET application opens a database connection. Calling Close method on the connection object in the finally clause ensures that the database connection is disposed after it has been used.  

SqlConnection conn = new SqlConnection(...)

try

{

   conn.Open();

   // do some processing with the connection   

}

catch(SqlException ex)\

{

   // do exception handling    

}

finally

{

   // close the connection

   if(conn!=null)

     conn.Close();

}

 


Additional Resources

Related Items

Use Try and Finally on Disposable Resources

CRM Service Utility for Mobile Development

Technologies

Dynamics CRM
Code Generation, Dynamics CRM metadata access
Desktop, Phone, Windows RT
en-US
9/8/2014

Introduction

This sample is a custom extension to the CrmSvcUtil.exe program that ships in the Dynamics CRM 2013 SDK. The purpose of this program is to generate C# or VB source code containing early-bound entity types and option set types from the metadata of your CRM server. This code can then be included in your mobile app projects. This enables you to make use of both out-of-box and any custom or customized entities in your code.

 

Building the Sample

To build the program, follow these steps.

  1. Obtain the CrmSvcUtil.exe program and the Microsoft.Xrm.Sdk.dll assembly from the Bin folder of the CRM 2013 SDK. You can download the SDK from http://msdn.microsoft.com/en-us/dynamics/crm/dn467921.aspx.
  2. Load the CrmSvcMobileUtil.sln solution file into Visual Studio 2013.
  3. Add references to CrmSvcUtil.exe and Microsoft.Xrm.Sdk.dll in the project.
  4. Press F6 to build the program.

 

Running the Program

For information on how to run the program, see the SDK topic: Create early bound entity classes with the code generation tool (CrmSvcUtil.exe).

 

Important Notes

    • The sample files are not intended to be used in a production environment. You should deploy this sample to a test environment and examine it for interaction or interference with other parts of the system.
    • This program was written by Kenichiro Nakamura at Microsoft.

       

      More Information

      For more information about writing an extension to the CrmSvcUtil program, see Create extensions for the code generation tool.

      You can download code:

      CRM Service Utility for Mobile Development.zip (48.2KB)