Granting Access to a Business unit Team via C#

Hi Folks,

I hope there isn’t any one who doesn’t know about security roles and access privileges being in Dynamics space. Most of the people should be aware of doing this via application, in this post, sharing one simple way to grant access to the records using C# code. Please use the below code to achieve the same.

private void ShareRecordtoBUTeamofRequestorUser(Guid Targetid, Guid TargetShare, IOrganizationService orgService)
                if (Targetid != null && TargetShare != null)
                    GrantAccessRequest grant = new GrantAccessRequest();
                    grant.Target = new EntityReference(MetadataHelper.VolunteerList.EntityLogicalName, Targetid);

                    PrincipalAccess principal = new PrincipalAccess();
                    principal.Principal = new EntityReference(MetadataHelper.Team.EntityLogicalName, TargetShare);
                    principal.AccessMask = AccessRights.ReadAccess;
                    grant.PrincipalAccess = principal;

                        //GrantAccessResponse grant_response = (GrantAccessResponse)orgService.Execute(grant);
                    catch (Exception ex)
                        throw ex;
            catch (Exception ex)
                throw ex;

I have commented below lines in try block above and avoid using them because you will get an error for the same…

GrantAccessResponse grant_response = (GrantAccessResponse)orgService.Execute(grant);

An unhandled exception has occurred during execution of the plugin.
An error occured while getting default Team of Requestor BusinessUnit[A]Microsoft.Crm.Sdk.Messages.GrantAccessResponse cannot be cast to
[B]Microsoft.Crm.Sdk.Messages.GrantAccessResponse. Type A originates from ‘Microsoft.Crm.Sdk.Proxy, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in the context ‘Default’ at location ‘C:\Microsoft.Crm.Sdk.Proxy.dll’. Type B originates from ‘Hisol.SCS.CRM.Plugins, Version=, Culture=neutral, PublicKeyToken=bb2727b96c9cb15e’ in the context ‘LoadNeither’ in a byte array.

Thank you.



Fetch more than 5000 records in one go…paging cookie way…but there’s a catch….

Hi Folks,

Hope some day or the other, every CRM Consultant will face this issue where they need to retrieve more than 5000 records in one go.

As every one in the internet suggests, paging cookie is the easiest way to achieve the same.

However here there is a catch…if you will use distinct=”false” no-lock=”true” along with your fetch query, you will never achieve the expected result and the timeout error keeps on popping up.

Pretty surely Microsoft have had documented this one, but I couldn’t find any relevant Microsoft article stating this. So thought of sharing this tip over my blog so that some day it will help some one. Here is the complete solution…

//Call the method to use Paging cookie and fetch multiple records in one go....
EntityCollection fetchDonationTransactionRecords = RetrieveAll(service, fetch);

/// <summary>
        /// RetrieveAll
        /// </summary>
        /// <param name="service"></param>
        /// <param name="fetchXml"></param>
        /// <returns></returns>
        public static EntityCollection RetrieveAll(this IOrganizationService service, string fetchXml)
            EntityCollection finalCollection = new EntityCollection();
            int fetchCount = 5000;
            // Initialize the page number.
            int pageNumber = 1;
            // Specify the current paging cookie. For retrieving the first page, 
            // pagingCookie should be null.
            string pagingCookie = null;

            while (true)
                // Build fetchXml string with the placeholders.
                string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
                EntityCollection recordsCollection = new EntityCollection();
                FetchExpression expression = new FetchExpression(xml);
                recordsCollection = service.RetrieveMultiple(expression);

                // * Build up results here *

                // Check for morerecords, if it returns 1.
                if (recordsCollection.MoreRecords)
                    // Increment the page number to retrieve the next page.
                    pagingCookie = recordsCollection.PagingCookie;

                    foreach (var record in recordsCollection.Entities)
                    // If no more records in the result nodes, exit the loop. 
                    if (finalCollection.Entities.Count >= 5000)
                        foreach (var record in recordsCollection.Entities)
                        finalCollection = recordsCollection;
            return finalCollection;

Hope this helps…that’s it for today…be safe & happy CRM’ing….



Missing Index – A factor to review before implementing performance changes


Have u ever faced any performance issue with any of your REST API hosted out in the internet. So here’s the background, our client has a Custom Asp.Net Portal(remembering the old day school of using Asp’s, interesting…??) which is built on using the REST API.

So this REST API was having some performance issues, this is where we got to check on the newly created entity for our API Implementation…after couple of hours of research, we found that few indexes are missing.

You should be knowing how it’s difficult to read a book without indexes, so in the same way, the C# code was finding it difficult to retrieve the data without any indexes and after adding them, the peformance had been improved and with a bit of code improvisation, we got a significant improvement in the performance.

For those trying to search for missing indexes, please try out the below code…


       CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],


       OBJECT_NAME(mid.[object_id]) AS [table_name],








       p.rows AS [table_rows],

       mid.[statement] AS [DatabaseSchemaTable],

         GETDATE() QueryExecustionTime

FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)

INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)

ON migs.group_handle = mig.index_group_handle

INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)

ON mig.index_handle = mid.index_handle

INNER JOIN sys.partitions AS p WITH (NOLOCK)

ON p.[object_id] = mid.[object_id]

WHERE mid.database_id = DB_ID(‘Starbucks_MSCRM’) –CHANGE DB NAME HERE –Starbucks_MSCRM

–AND mid.[object_id] = OBJECT_ID(‘dbo.ign_transactionbase’) –CHNAGE TABLE NAME HERE



Hope you found some interesting scenario to deal with your performance issues.



Using Custom API as a trigger for Flow

Dropping new goodies straight to Microsoft Docs, without any formal announcement, has now been normalised. Couple of Virtual Table features have been “announced” without much fanfare this way. The ability to trigger Flows from Custom API is one such unannounced feature. Custom API is a feature in Dataverse that is very similar to Custom Process […]

Using Custom API as a trigger for Flow

Cancel the save based on the result of an asynchronous operation

In 2017, Natraj Yegnaraman shared a clever method to cancel the save of a form. His approach was to cancel the save before the asynchronous operation and then retrigger the save if needed after the asynchronous operation is resolved. You can find all the details on the following link. This approach is explained by the […]

Cancel the save based on the result of an asynchronous operation

Tips for overcoming your problems working with SSRS Reports

Recently I have worked on some complex Fetch XML based SSRS reports, below were some basic tips to be kept in mind when you were working on a similar reporting project.

Things to take a note:

  1. When working with Prefiltered reports, make sure you add the prefilter at the beginning of the report dataset query.

2. Download report from CRM

Wondered how to edit an existing report, you can download the same from CRM, add it to your visual studio and edit your fetch xml report.

3. Missing reports for other users

Make sure you set the Report viewable by for the report.

4. Report missing records:

Tip: check if all main report and sub report parameters are same…even verify if multiple values are enabled for parameters is enabled for main report, it should be enabled for sub report parameters also.

5. Use Lookup and Lookupset necessarily accordingly to the need, do note its drawbacks before confirming your design and proceeding with development as it wont allow nested lookups…etc.

6. When comes to Testing the reports, test the report is CRM and not in the Visual studio.

7. Reports were run on the browser and they were browser specific, based on the user’s region, it will be rendered.

8. Make sure to add the same queries used in the main report to the sub report for Production uses.

9. Apply row or column grouping accordingly based on the requirement.

10. If data is being missed in some of the columns, make sure you check if there is any issue with the parameters, try to verify the sub report by validating the queries from the query designer and passing appropriate values to the parameters as and when required.

11. As we cant troubleshoot the SSRS Reports, the only way we can check and verify if by printing values obtained from the datasets.

12. Double check the Dataset properties if you still see any discrepancy with the parameters and their order as this is important when you have dependent parameters for executing your dataset.

13. You can add filters to your dataset from the dataset properties itself if required.

14. Make sure to click of refresh fields in the dataset properties window as and when if you update any dataset query.

15. Also note that SSRS reports are cached, one other way to clear your cache and re-run the report.

16. You can use built in fields if you want to display any of the report based data.

17. If you have changes in any of the sub reports, you don’t need to push all the report changed including the Parent report, instead you can add only the changed sub report to the solution and move across.

Hope one of the above tip had helped you in your project, that’s it for today…till then keep CRM’ing and be safe.

Thank you.



Custom workflow to find the logged in user role

Hi Folks,

Have you ever got a requirement to find the user role before running any logic using workflows, then this post is for you. Please continue reading.

If suppose, you got to have to run a workflow to validate some of the business scenarios using a workflow, then verifying the logged in user role is not possible using OOB workflow. In this case, you would need to get this up and running with the help of Custom workflow at first place and once the role is verified, you would need to trigger your OOB workflow logic.

Custom workflow design: The custom workflow accepts an mandatory output parameter which returns a bool value if the logged in user security role matches.

The code can be found at my GIT Hub, please check it out in case you want to implement the same requirement, you can pass in the input parameters or add any additional output parameters according to your business needs.

Then you would need build this assembly by signing it, next part would be to register in your CRM with the help of Plugin registration tool.

Later you can refer the same library in your OOB workflow as below..

And you nailed it…that’s it for today, please stay tuned and be safe..

Happy CRM’ing…



Power FX…get back your power with excel like formulas… A brief review…

Microsoft Power Fx is an open-source programming language that hopes to make coding as straightforward as building a spreadsheet. Wondered why Microsoft is bringing this excel backbone language to Power Platform range of Products & Services.

It is planned to expand Power Fx throughout the Power Platform over the next two years, including model-driven Power Apps, Microsoft Dataverse and Power Virtual Agents, Microsoft’s low-code chatbot platform. Developers will also be able to use it to directly edit apps in text editors like Visual Studio Code.

So Power Fx is the new name for the formula language for canvas apps. It’s a general-purpose, strong-typed, declarative, and functional programming language. Power Fx will be made available as open-source software. And source code can be found at this link..

When a formula is modified or a value is entered, the worksheet is immediately recalculated to reflect the changes. 

Let’s look more in-depth at all the things that Power Fx is doing for us and the freedom it has to optimize because the formula was declarative:

  • Asynchronous: All data operations in Power Fx are asynchronous. The maker doesn’t need to specify this, nor does the maker need to synchronize operations after the call is over. The maker doesn’t need to be aware of this concept at all, they don’t need to know what a promise or lambda function is.
  • Local and remote: Power Fx uses the same syntax and functions for data that’s local in-memory and remote in a database or service. The user need not think about this distinction. Power Fx automatically delegates what it can to the server, to process filters and sorts there more efficiently.
  • Relational data: Orders and Customers are two different tables, with a many-to-one relationship. The OData query requires an “$expand” with knowledge of the foreign key, similar to a Join in SQL. The formula has none of this; in fact, database keys are another concept the maker doesn’t need to know about. The maker can use simple dot notation to access the entire graph of relationships from a record.
  • Projection: When writing a query, many developers write select * from table, which brings back all the columns of data. Power Fx analyzes all the columns that are used through the entire app, even across formula dependencies. Projection is automatically optimized and, again, a maker doesn’t need to know what “projection” means.
  • Retrieve only what is needed: In this example, the LookUp function implies that only one record should be retrieved and that’s all that’s returned. If more records are requested by using the Filter function—for which thousands of records might qualify—only a single page of data is returned at a time, on the order of 100 records per page. The user must gesture through a gallery or data table to see more data, and it will automatically be brought in for them. The maker can reason about large sets of data without needing to think about limiting data requests to manageable chunks.
  • Runs only when needed: We defined a formula for the Text property of the label control. As the variable selected changes, the LookUp is automatically recalculated and the label is updated. The maker didn’t need to write an OnChange handler for Selection, and didn’t need to remember that this label is dependent upon it. This is declarative programming, as discussed earlier: the maker specified what they wanted to have in the label, not how or when it should be fetched. If this label isn’t visible because it’s on a screen that isn’t visible, or its Visible property is false, we can defer this calculation until the label is visible and effectively eliminate it if that rarely happens.
  • Excel syntax translation: Excel is used by many users, most of whom know that the ampersand (&) is used for string concatenation. JavaScript uses a plus sign (+), and other languages use a dot (.).
  • Display names and localizationFirst Name is used in the Power Fx formula while nwind_firstname is used in the JavaScript equivalent. In Microsoft Dataverse and SharePoint, there’s a display name for columns and tables in addition to a unique logical name. The display names are often much more user-friendly, as in this case, but they have another important quality in that they can be localized. If you have a multilingual team, each team member can see table and field names in their own language. In all use cases, Power Fx makes sure that the correct logical name is sent to the database automatically.

These no-code tools have been built to read and write Power Fx to ensure that there’s plenty of headroom for someone to take it further.

Now lets see what’s in there for developers here…

Professionals want to use professional tools to be most productive. Power Fx formulas can be stored in YAML source files, which are easy to edit with Visual Studio Code, Visual Studio, or any other text editor and enable Power Fx to be put under source control with GitHub, Azure DevOps, or any other source code control system. Take a look at below…

What a cool feature that Microsoft introduced all the excel functions and formulas to make low code apps. much easier ..if you want to further read regarding this…Microsoft Learn is the right place…this link can take you there…

That’s it for today…



Getting started with the Azure IoT Central Rest API

Sander van de Velde

Azure IoT Central is a SaaS platform for IoT projects.

If you are looking for a way to manage and monitor your IoT devices outside the Azure Portal or are not able to build your own IoT platform, IoT Central is the place to be. And you can extend this portal with custom Azure resources using the export functionality.

All you need is to have browser access to Azure IoT Central. You can even run it for free for seven days to test it out. Also, the first two devices registered are free too.

Once you have worked with Azure IoT central, you have mastered it using the portal. If you want to scale up eg. the number of devices or users, automation of your tasks becomes necessary.

For this, Azure IoT Central offers a Rest API.

Let’s check this API out.

View original post 881 more words

Latest in Azure IOT this Ignite 2021

Hey Guys, this post is to introduce the new thing Azure Precept announced in this Ignite by Microsoft.

To know about Azure Precept in Depth, you can…follow the below links to check this out..

  1. Simplify Wi-Fi IoT device onboarding with Zero Touch Provisioning
  2. Under the hood with Azure Percept: Deploy edge AI to IoT devices in minutes
  3. Advanced Development with Azure Precept

This increases/enhances the Azure IOT product by deploying AI to IOT Edge Devices at a high level.

What a wonderful enhancement this is…can’t wait from trying out these….


Azure Percept

Wi-Fi Easy Connect™ | Wi-Fi Alliance (

Aruba ZTP solutions

Please feel free to share your thoughts or ideas on Azure Precept…I would be glad to assist you on this…