How to limit memory allocation

Congrats, you just upgrade you application from x86 to x64.

Now is less probably to have an OutOfMemoryException but you may have now another problem: use all the available memory with possible impact on other processes that are running on the system or on other users that are using your application.

In this post I want to show you one option to limit the process to a certain quantity of RAM: JobObjects

A job object allows groups of processes to be managed as one unit, but in our case we are only attaching one, our target process. It is possible to attach the current process to a job object, but any process can be attached to it (a process you started or identify one by its name).

I invite you to check the sample source code (c#) that can be found here.

It is important to set the BasicLimitInformation.LimitFlags to JOB_OBJECT_LIMIT_PROCESS_MEMORY(0x00000100) otherwise this will not work.

Conclusions: There are situation when you want to set a maximum limit of how much memory your application can allocate e.g. a background service that shouldn’t overload the system. This should be used with caution and if your x64 application is using all the available memory this may be a sign of a memory leak.

JobObjects represents a quick way to set this up. For more complex allocation problems you may consider to implement a custom CLR Host where you can not only limit the memory allocation but you can also control how is allocated.

Develop and use a windows service with Dynamics CRM

As mentioned in a separate post, when dealing with complex logic in Dynamics CRM, the right way to go is to isolate the complex part of your functionality in a separate windows service and consume it from your CRM.  In this article I will present the overall implementation guidelines / architecture of this approach.

As the first thing, let’s assume an use case. We want to implement a booking system with Dynamics CRM, and one of the core functionalities is calculating the booking price, that hides a complicated logic behind the scenes. Developing this with a plugin is cumbersome as the calculation routine can depend on many parameters and might always be a subject of changes, as you will often have to enhance your algorithm.

Now let’s build the implementation plan! (Please note that just the big pieces are presented. The details will follow)

  1. Create a C# Library that would implement the complex logic, and specifically, the function
    public static decimal CalculatePrice(string resource)
     decimal price = 125.50m;
     // Implement your logic
     return price;
  2. Create a Web API method to provide access to the business logic:
    public class BookingController : ApiController
     public IHttpActionResult CalculatePrice(string resource)
     decimal price = Booking.CalculatePrice(resource);
     return Json( price );
  3. Create a javascript resource to call the Web API method
    function CalculatePrice(resource) {
     $.get("https://localhost:9876/api/Booking/CalculatePrice?resource=xyz", function (data) {
     $("#price").html("The calculated price is:" + data + " EUR");
  4. Create an HTML resource that will call the javascript and display the result:
    <meta charset="utf-8" />
    <script src="Booking.js"></script>
    <script src=""></script>
    <input type="button" id="calculate-btn" onclick="CalculatePrice()" value="Calculate Price" />
    <div id="price">.....</div>

As a bonus, here is a nice image for you:


Implementing complex logic in CRM

CRM provides several possibilities to extend the standard functionality with custom written code – Plugins, Workflow Activities and javascript libraries.  However, when it comes to complex logic, you will find great difficulties in using plugins or workflows. Let’s say you have an Use Case when you have to generate thousands of records (say invoices), map them to other records (say Accounts) and create other thousands of Activities – all in one shot (say when the user clicks a custom button on your toolbar)! Why plugin might not be the best choice?

  • Plugins are hard to debug. One of the nightmares of CRM developers is to track an exception that happened inside a complex plugin – logging is limited and debugging is cumbersome or even impossible
  • Plugins / Workflows time out. If you write complex logic in your plugin that has to read / insert / updates many records, you have no predictability about what will happen when your database will reach millions of records. It might happen that your plugin execution time will reach the timeout limit and re-engineering / optimizing your plugin would be a task that you’d want to avoid.

The reasons listed above might be enough to make you think of alternatives. What I find as a good approach (I used it in my CRM projects) is to isolate the complex logic inside a windows service and call the logic from CRM context (plugin / workflow / javascript). A step by step description follows:

  • Build your windows service. Encapsulate the complex CRM logic inside your windows service, add a lot of logging and make your code testable
  • Expose the windows service functionality via a Web Api hosted inside your windows service
  • Call the Web Api from your plugins or javascript code

CRM - complex logic

A slightly different version of the above is not to use  a windows service, instead replace it with a classical WebService that would expose the complex logic. It is just a matter of preference. I find windows service approach slightly better, because I do not need to rely on IIS (making the architecture more flexible) as first note. As second note – usually when you have to deal with complex tasks in CRM, you might be asked to create different daily or import procedures, which normally would reside inside a windows service.

Please also note that the above apply only to CRM On Premise. If you have to deal with CRM Online, then you will need to adapt your architecture to Azure ecosystem. Things become more complex with CRM Online (because you will not be in the same network, as it is mostly the case with CRM On Premise) but for sure a similar solution can be found for CRM Online.

Choosing the appropriate CRM account for your helper Windows Service / Console Application

One of the common practices when building medium/ large Dynamics CRM applications is to develop a helper Windows Service or Console Applications that would take the burden of complex tasks, like generating large sets of data or cleanup jobs. Any piece of functionality that would be too complex to reside inside a Plugin can be isolated into a Windows Service logic, where you have much more control and debugging / tracing power. You can expose this complex functionality through a Web Service (usually hosted inside your Windows Service) and call the Web Service method from your plugin or a Javascript resource. You can find out about the benefits and implementation details here.

First thing you will have to deal with in this scenario is how do you authenticate to CRM?  Apparently an easy question, but you should consider the following aspects:

  • Every CRM account (well, almost every) costs. Sou you cannot just go and create a dummy account for your service and use it for CRM authentication – it will simply cost you or your customer additional 30-50$ / month
  • You could use the Administrator account, but what you really want is to keep track of who exactly made what exactly changes to your data. In other words, if you use your Administrator account for everything, long term you will lose trace-ability of your data, and that could become a issue hard to ignore in certain situations. As a good practice, you should always be able to know – who and when added / updated or deleted your data., therefore, having a specialized account for your Windows Service is always a good idea.


The solution  is to create a non-UI free CRM account. It is free, because its only purpose is to be used in scenarios as described above – this account cannot be used by human users.
Note: I am using Dynamics CRM Online 2016.

First, create a new Dynamics (Office365) account:

Create new Dynamics CRM Acccount

Assign the appropriate roles to the newly created user (like System Administrator)

The last thing to do is to make the user Non-Interactive, which is the key thing to do, as it won’t require your company to pay for the account.

User Service - Non Interactive

Now your account is ready to be used:

<add name="MyCRMServer" connectionString="AuthType=Office365;Username=service@****; Password=***;Url=https://***" />

//Use the connection string named "MyCRMServer" from the configuration file
 CrmServiceClient crmSvc = new CrmServiceClient(ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString);
 var response = crmSvc.OrganizationServiceProxy.Execute(new WhoAmIRequest());