Retrieve and Create Attachments Associated To Notes of an Entity in Dynamics CRM

You may have a need to retrieve attachments and create attachments associated to notes of an entity in Microsoft Dynamics CRM. We have provided the sample .net code that shows how to retrieve these attachments:

Sample 1

EntityCollection RetrieveNoteAttachments(Guid entityId)


EntityCollection results = null;

QueryExpression _noteattachmentQuery = new


EntityName = "annotation",

ColumnSet = new




Criteria = new


Conditions =




AttributeName = "objectid",

Operator = ConditionOperator.Equal,

Values = {entityId}




AttributeName = "isdocument",

Operator = ConditionOperator.Equal,

Values = {true}





using (var service = new



results = service.RetrieveMultiple(_noteattachmentQuery);


return results;



entityId=Guid/ID of the entity in CRM for which we are retrieving the attachments

CRMConnection= The connection string to connect to the CRM org for which we are connecting to.


Sample 2

Here is the sample .net code that shows how to create a note with attachment in CRM for an entity:

Guid CreateNoteAttachment(string subject, Guid entityId, string filename, byte[] data)



Guid attachmentId = Guid.Empty;

Entity note = new




note["objectid"] = new
EntityReference("contact", entityId);

using (var service = new


attachmentId = service.Create(note);


return attachmentId;



entityId=Guid/ID of the entity in CRM for which we are retrieving the attachments

subject= Subject of the note that we are creating

filename=The name of the file we are attaching to note

data=the content of the file we are attaching to note

CRMConnection= The connection string to connect to the CRM org for which we are connecting to.


Note: In case we are using the code in a plugin, we can use the instance of the IOrganizationService to connect to Dynamics CRM.

We hope you find this topic as helpful and informative as we do! For even more information check out another blog we think will be helpful for you:

Access Team View in Dynamics CRM

Have you been using the exciting new Access Team feature in CRM 2013? Here are some quick steps to create a view to display records where you are a member of the Access Team, making your use of them even better! The example used for this blog, is on Account records.

First you will have to make sure you have Access Teams configured for your entity. Please reference our previous blog post here on Implementing Access Teams in Dynamics CRM 2013.

On the below Account, you will see that we are on the Account as an Access Team member:

Access Team View in Dynamics CRM
Our default view currently shows My Active Accounts where we are the Owner, but we want to also see Accounts where we are on the Access Team. You will notice that the Account above (12345 Cherrywood Lane) is not displayed.

Access Team View in Dynamics CRM

So create the view below:


  1. Look for Accounts and select a New view.
  2. Select Teams- Regarding Object ID – you will find this in the Related Options (below all of the Entity Fields which are displayed in the drop down first).
  3. Select Team Type and set the criteria to Equals Access
  4. In the next row that appears, select Users – you will find this in the Related Options after all of the Fields Options.
  5. In the next row that appears, select User from the Fields options and set the criteria to Equals Current User.
  6. Save the New View and name it whatever you please.
  7. Navigate back to the entity you created the view for and Select the View.

Since the view was created for the Account Entity, you can now see a list of all Accounts that account for Access Team membership.

Access Team View in Dynamics CRM

And there you have it. You can now see a list of records where you are on the Access Team in a quick and easy manner.

Please keep your eye out on our blog for additional tips and tricks to enhance your CRM experience, as well as for education and other Microsoft Dynamics CRM updates.

Happy CRM'ing!

Sitemap Contains Reference to an Entity Not Found in the Metadata Cache

You may encounter an error where the sitemap for Organzation xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx contains a reference to the entity "entity_name," but that entity was not found in the metadata cache.

This error shows up in the Application Event Log of the CRM web server when there are references to entities that do not exist in the sitemap. The most common reason for this issue may be when customizations are moved between environments and entities get deleted in this process, but the sitemap still has references to them. Below are the steps to resolve this error and stop the errors from appearing in the Event Log. It's a good way to keep things clean in the CRM sitemap.

  1. Go to the Application Event Log of the CRM server and copy the GUID of the Organization and the entity name which is throwing the error. (Ignore this step if there is only one organization.)

    Entity Not Found in the Metadata Cache

  2. Find the name of the Organization by querying the CRM database using the following statements. (Again, ignore if there is only one Organization.)

    from Organization where ID=
    'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'[Enter the organization ID you found in the event log]

  3. Create a new unmanaged solution with just the sitemap and export the solution for the organization identified in step 2 (or just the organization if it is the only one).

  4. Make a back-up of this solution if something goes wrong with editing the XML and you need to revert to its original state before the change. Unzip the files of the solution and open the customizations.xml file.
  5. In the XML, search for the entity name found in the event log and see if there are any tags that start with "" or "" or "". Basically, look for all the references of this entity name, and remove those sections from the sitemap.
  6. Once all the reference are removed, re-package the solution (remember, you need to create a zip file of all the files in the unzipped folder) into a new .zip file and import it back into CRM.

  7. Finally publish the customization upon successful import. This should fix the error.

It's important to note that the user performing the above process must have the following privileges:

Also, when deleting anything in Microsoft Dynamics CRM, always back up the customizations. You might specifically back up the sitemap before editing and re-import this solution in case something goes wrong with the sitemap update.

Happy CRM'ing!

Using a Custom Entity to Track Status Changes in CRM 2011

Dear JoeCRM,

I want to track the different phases/statuses of an opportunity, and I also need to be able to report on those changes. The auditing feature is very useful for many things, but it can't be easily displayed in an advanced find or a dashboard.

Have any suggestions to track status changes in CRM 2011?

Status Auditor

Dear Status Auditor,

I have very simple solution for you. With a custom entity and a workflow, you will have your reporting capabilities and advanced find with a snap of your finger!

Since you mentioned opportunities above, we will focus on that entity and the status reason field.

1. First, we need to build a new custom entity to store these values. Within this custom entity, we will create a couple of fields that will give use some further query capabilities, in addition to using some of the out of the box fields such as owner and created on date fields.

  1. We will use the primary field to store the status
  2. A lookup to the Opportunity Entity
  3. A lookup to the Account Entity

2. Now that we have the relationship between the Opportunity and this custom entity, we can now build a workflow to create these records.

3. When setting up the workflow, we are going to check off three things: the "As an on demand process" (which allows us to run the workflow on existing records), when the "record is created," and when the "record field changes" (select status reason).

create workflow to track status changes in CRM 2011

4. Now we will create a step. We will create a new record in the custom entity we built in step 1. We can set the Opportunity, Account, Status and the owner (modified by field) from the Opportunity record.

Using a Custom Entity to Track Status Changes in CRM 2011

5. With this workflow activated, the records will be created automatically for us as the record statuses change.

Now when we review this custom entity, we can see what the status reason was changed to, the person who changed the value, and when it was changed. With this data, you can create reports and advanced finds. You also will have the capability to review the status changes by selecting the custom entity in the left navigation of the Opportunity.

Using a Custom Entity to Track Status Changes in CRM 2011

Using a Custom Entity to Track Status Changes in CRM 2011

So there you go! This just one of the many examples of using custom entities to store additional information in CRM.

Happy CRM'ing!

How to Customize Sorting Priority in System Views and Personal Views in CRM 2011

You can do a lot with views in Dynamics CRM, and we've got several posts on these features already. You can create and hide shared views, deactivate and remove system views, or quickly sort your view with filtering. But what if you're tired of looking at a view and finding the list sorted by "Date" instead of by "Company Name" or "Revenue" or any other column that you would prefer instead? Good news! Any user of CRM can customize how their personal views appear.

There are two ways to change personal views: Option one is simply clicking on the column heading you would like to sort by, thereby sorting the column in ascending or descending order. This needs to be done every time you enter the view. Who has the time or patience for that? Every single time?! Not this guy. There's got to be a better way.

The most effective way to do this is to customize the view. This can be accomplished with a few easy steps:

  1. Find the view you would like to customize.
  2. Click the Customize tab, then select View at the top of the screen: customize sorting priority for views in CRM 2011

    (It is important to note that a user with System Administrator rights can make changes to the company-wide System View. To do this, instead of selecting "View," select "System Views" in the top ribbon, and then select which system view to make changes to on the popup that follows. The following steps remain the same from there.)

  3. This will open a popup giving you customization options for the view.
  4. Select "Configure Sorting":

  5. Another popup will appear, giving you sort options based on the columns in the view.
    1. The first selection is your first sorting priority – in this case revenue.
    2. The second selection determines how to sort the view in the event of duplicate values, customer, user, etc.
    3. Click OK after making your selections.

  6. After clicking OK, click "Save and Close" on the popup, then click "Publish Entity" on the ribbon at the top:

  7. Refresh your browser window, find the view again, and you are all set – no more annoying sort results, and a much more efficient way of viewing your data – the way you want it!

It is small customizations like this one that make use of Dynamics CRM even more valuable, and why Dynamics CRM continues to be the best CRM system on the market. Keep checking back for more tips and tricks on Dynamics customizations, or let us know how we can help!

Happy CRM'ing!

Searching for Accounts or Contacts Without Opportunities in CRM 2011

In Microsoft Dynamics CRM, searching for records that meet specific criteria is really straightforward. However, people often want to search or report on records where data does not exist. The most common example is prospects without Opportunities. There isn't a direct way to search for the absence of the Opportunity record, but with a few extra steps and the use of a marketing list, users can easily create this list. Without further ado, here is how you can search for accounts or contacts without Opportunities in CRM 2011!

  1. Create a static marketing list for the correct entity for your prospects. This could be Accounts or Contacts depending on how your organization works.

    Static is the default setting for marketing lists. What this means is that this list will not reference changes to your search criteria. (Opportunities added after this list is created will not be reflected. This is a snapshot in time.)

    In my example, the prospects exist in the Account table.

    Searching for accounts or contacts without opportunities in CRM 2011

  2. Manage the list's members by clicking on "Marketing List Members" and then the "Manage Members" button on the ribbon.

  3. Use Advanced Find to add all the possible prospects to the list. In my example, I'm looking for all active Accounts. If you are looking for specific criteria like Customers in Texas without Opportunities, then this is where you would specific Texas as part of your possible prospects.

    (Note: If you selected "Contact" as the member type is Step 1, this search should be against Contacts instead of Accounts.)

  4. Select all the returned values to add to the list.

    And the values are added to the list.

  5. Remove the Accounts with Opportunities.

    As mentioned previously, it's easy to search for criteria where the data is present, so in this case, users can search for the values with Opportunities and subtract them from the list.

    1. Press the Manage Members button on the ribbon again

    2. Select Use Advanced Find to remove members.

    3. When selecting the entity, the related Opportunity will be at the bottom of the entity list under the "Related" heading.

  6. Select the values to remove from the list.

  7. The selected values are removed.

Congratulations! The list that remains is the list of prospects without Opportunities. It looks like this super sales team has open Opportunities for about half their customers.

Happy CRM'ing!

How to programmatically set the status code field of a Dynamic entity

If you are working on creating or updating a dynamic entity in Microsoft Dynamics CRM and got stuck on properly setting the statuscode field please read further:

Assigning value to the statuscode fields is not same as assigning any other fields programmatically. It needs a bit of trick. Statecode and statucode fields in CRM are tightly related and they go hand on hand.

Let us consider a setting like this:

Statuscodename Statuscode
Open 1
Done 2
Canceled 3
Scheduled 4
statecodename Statuscode
Open 0
Completed 1
Canceled 2
Scheduled 3

Let us set the statuscode of a dynamic entity say "new_smartappointment" to done. CRM does not allow us to just set the status code to "Done". We also have to set the statecode to completed. To set these state code and status code we need to use SetStateDynamicEntityrequest class.

And here is how we do it:

SetStateDynamicEntityRequest req = new SetStateDynamicEntityRequest();
Moniker n = new Moniker { Id = id, Name = " new_smartappointment " }; // id here is a variable that stores the GUID of the record to be updated.
req.Entity = n;
req.State="Completed" //set the statecode
req.Status=2 // set the status code.
SetStateDynamicEntityResponse res = (SetStateDynamicEntityResponse)service.Execute(req);

Hope that helps some of you out there.

Happy CRM'ing!

Error Customizing CRM 2011 Entity Form

While working on a Microsoft Dynamics CRM 4.0 to CRM 2011 upgrade we encountered this error while trying to customize the CRM 2011 entity form:

Error: Exception of type 'System.Web.HttpUnhandledException' was thrown.

Error Message: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Error Details: Exception of type 'System.Web.HttpUnhandledException' was thrown.

Source File: Not available

Line Number: Not available

Request URL: http://servername/orgname/tools/formEditor/formeditor.aspx?action= &formtype=main&objectTypeCode=3&pagemode=iframe&sitemappath=WorkplaceMyWorknav_dashboards

Stack Trace Info: [NullReferenceException: Object reference not set to an instance of an object.]

at Microsoft.Crm.Application.Controls.FormEditorBase.AddPlaceHoldersInSection(XmlNode& secNode)

at Microsoft.Crm.Application.Controls.FormEditorBase.AddSpacerCellsInSectionIfRequired(XmlNode& secNode)

at Microsoft.Crm.Application.Controls.FormEditorBase.AddColumnsAttribute(XmlNodeList& nodeList)

at Microsoft.Crm.Application.Controls.FormEditorBase.ValidateFormXml()

at Microsoft.Crm.Web.Tools.Views.FormEditorPage.ValidateFormXml()

at Microsoft.Crm.Web.Tools.Views.FormEditorPage.GetFormXml(String formXmlString)

at Microsoft.Crm.Web.Tools.Views.FormEditorPage.ConfigurePage()

at Microsoft.Crm.Application.Controls.PageManager.OnPreRender(EventArgs e)

at System.Web.UI.Control.PreRenderRecursiveInternal()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Fortunately, Microsoft seems to have already encountered this issue, we found this post on the MSDN blogs:

In this post we will expand on Microsoft's post to make it easier for the CRM community to understand.

Disclaimer: This article describes manually editing the configuration file for CRM. Making mistakes here can have devastating effects on your CRM system and is considered advanced work. Be sure to save a copy of your original export file in a safe place before making any changes to the XML. If this kind of work makes you feel queasy, ask for help from someone who is more technical.

The problem is a discrepancy between the rowspan attribute on the cell tag and corresponding row tags in customizations.xml.

Let's look at the XML for the Description field on our Opportunity Form

CRM 2011 Error Customizing Entity Form

Notice how the value of rowspan (5) matches the number of row tags in the XML? This is good XML.

Now since I like you all so much, I am going to break my XML to show what happens. Let's take one of those tags out, save the file, compress it, import it into our CRM system and Publish.

When I try to customize the main Opportunity form here's what I get:

If you don't have development errors enabled, you'll just see this, but I would get the error above if I were tracing this error.

To fix this problem we need to get the customizations.xml for the entity that is giving you trouble. Go to Settings, Customizations, Solutions. Create a new, unmanaged solution and add the entity that is producing the error. You will not need to include required components; in fact, you'll be glad that you didn't. Export the solution, extract the files and open customizations.xml with a XML text editor.

Now for the tedious part: Perform a search for rowspan= and find the section or sections that contain a rowspan count attribute that is greater than the number of tags for the section. Here's where not including required components is going to save you time. When you find the section that has fewer row tags than rowspan specifies, just go ahead and add another set of tags before the last one. Complete your search for additional rowspan attribute to row tag discrepancies and then reimport the solution to your CRM system. This will fix the error above.

We hope you found our explanation helpful. If you're encountering this error and would prefer the help of a CRM professional to resolve it, give your CRM super heroes a call!

Happy CRM'ing!

A Tip for Notes When You Create a New Dynamics CRM Entity

When you create a new Dynamics CRM entity, you have the option to select Notes and Activities to add to each record.

add a new dynamics CRM entity

If you aren't sure if you want to display Notes and Activities on the entity, leave them unchecked. You can always circle back and add Notes and Activities to your entity

If you choose to check off the Notes and Activities Boxes and click Save the Notes and Activities boxes will become greyed out.

Dynamics CRM

Let's say for example you choose to add Notes and Activities, but later on….. you decide to remove Notes from your entity.

Easy enough:

Go to Settings > Customization > Customize the Solution > Select your entity in the Entity section > Click Forms and edit the Main Form.

To Remove the Notes from your Form

  1. Select the Notes Section on the form
  2. Select the Remove button from the Action Ribbon
  3. Click Ok

Notes have been removed.

Later, time has passed and your requirements have once again changed. You need to add Notes back to your entity.

You go to Customization> Customize the Solution > Select your entity but notice the Notes checkbox is still greyed out.

You open the Main Form; you see that there is no Notes field or Notes section. You start to question "is it possible to add Notes back to your entity?"

Yes it is.

Open up the Main Form in the left hand navigation

  1. Select the Insert Tab across the top
  2. Click on the Notes button

By clicking on the Notes Icon it will re-add the Notes section to the entity.

Inset a Tab if you choose to add the Notes section to a different Tab, or add Notes to an existing section already on the form.

Hope you enjoyed this CRM How to from the CRM Experts at PowerObjects. Feel free to comment and let us know if there are other areas of crm tips and tricks  you would like us to conver in future posts.

Happy CRM'ing!

Party List fields and how to filter Custom Activity records that use them using Advance Find

A new feature in Microsoft Dynamics CRM 2011 is the ability to create Custom Activity entities. You can create a custom activity entity by checking the Define as an activity entity field.

CRM Advanced Find

While working with a Custom Activity entity you may notice some fields of type Party List such as Customers, Partners, and Organizer (for more information please visit Party List Types).

CRM Party List

When added to the form you may notice that these fields look like Lookup fields but may function a little different. For example the Partners or Customer party list fields let you select multiple records of the same or different type.

You may also notice there aren't any 1:N relationships defined for these Party List fields. This is because these fields point to the Activity Party table. Anytime a record is added to the Party List fields an associated record is created in the Activity Party table.

You can use the Activity Party table to get a complete view of all the Part List participants.

To retrieve Custom Activity records for only a certain participant in a Party List you can use Advance Find. For example, the use of Advance Find will search for all records that have John Doe in the Customer Party List. From the Custom Activity select Activity Parties form the related list.

Then select Party (Contact) from the related list. Select the Full Name field and enter the name of the Contact then click the Results button.

That's all there is to it. No need to be a CRM Expert.

Happy CRM'ing

CRM 2011 Remove Notes & Attachments, Connections and Activities from an Entity

Before we get to the CRM 2011 remove notes, connections, etc. functionality, let's keep in mind a fine print warning.

warning for CRm 2011 remove notes & attachments

All is well as long as you heed the warning, but as it so often happen, we tend to conveniently forget until long after we have developed a bunch of attributes, relationships, forms, JavaScripts, workflows and even plugins and then it hits us – we really do not need connections, notes & attachments or activities for that entity! Then why were they enabled in the first place, because Connections, Notes & Attachments and Activities are checked by default.

Now that we have done that cannot be undone, we come to the topic of this blog. How to in CRM 2011 remove Notes & Attachments, Connections and Activities from an Entity, well without doing the obvious – drop the entity and recreate it.

A couple of notes of caution before we dive into the How To's


How to:

To Remove Connections

Make the following XML Tags changes in the Customizations XML
Entities > Entity - Select the Entity you need > EntityInfo >
Modify <IsConnectionsEnabled>1IsConnectionsEnabled>
Set the Value from 1 to 0
Delete <EntityRelationship Name="EntityName_connections1"> node
Delete <EntityRelationship Name="EntityName_connections2"> node
Replace the Entity Name above and remove the entire node

To Remove Notes and Attachments

Make the following XML Tags changes in the Customizations XML
Entities > Entity - Select the Entity you need > EntityInfo >
Delete <HasRelatedNotes>TrueHasRelatedNotes> node
Entities > Entity - Select the Entity you need > FormXML > forms type = "main" > systemform > form > tabs > tab > labels > label > Description = "Notes"
Delete Entities > Entity - Select the Entity you need > FormXML > forms type = "main" > systemform > form > tabs > tab
This can also be done after importing the solution - Open the Entity for customization > Goto the Form and Delete the Notes Tab
Delete <EntityRelationship Name="EntityName_Annotations"> node
Replace the Entity Name and remove the entire node

To Remove Activities

Make the following XML Tags changes in the Customizations XML
Entities > Entity - Select the Entity you need > EntityInfo >
Delete <EntityMask>ActivityPointerEntityMask> node
Delete <HasRelatedActivities>TrueHasRelatedActivities> node
Delete <EntityRelationship Name="EntityName_ActivityPointers"> node
Delete <EntityRelationship Name="EntityName_Appointments"> node
Delete <EntityRelationship Name="EntityName_Emails"> node
Delete <EntityRelationship Name="EntityName_Faxes"> node
Delete <EntityRelationship Name="EntityName_Letters"> node
Delete <EntityRelationship Name="EntityName_PhoneCalls"> node
Delete <EntityRelationship Name="EntityName_RecurringAppointmentMasters"> node
Delete <EntityRelationship Name="EntityName_ServiceAppointments"> node
Delete <EntityRelationship Name="EntityName_Tasks"> node
Replace the Entity Name
This also needs to be done for any custom activities that you may have created - Replace the Entity Name and the Custom Activity Name
Delete <EntityRelationship Name="EntityName_CustomActivities">

Campaign Response is the only exception - but this is associated with only Account, Contacts and Leads.

Hope this helps. Check our Microsoft Dynamics CRM Expert blog often for helpful tips and tricks.

Happy CRM'ing!

When to use a Global Option Set vs. a Custom entity

One of the great features in MS Dynamics CRM 2011 is Global Option sets. A global option set, sometimes called a global pick list, provides a common set of options that can be used by multiple entities to set attributes. This is a great feature but there is a draw back from using the Global Option set instead of a custom entity. If a user or organization decides to change or delete those values in the option set, the existing data that was entered using those values will be deleted from the system. If those values will be changing, the best approach would be to use a custom entity. This will change the look of the field from a drop down menu to a lookup but the advantage of using the custom entity is that you have the ability to "deactivate" a record instead of deleting it. Now if the user or organization were to delete the record from the custom entity you would still have the same issue with the Global Option Set. Another benefit is that you have the ability to activate the record if you ever decide to use that value again.

In this example for MSCRM, we will walk through creating a Global Option set, a custom entity for a lookup as well as show you how to deactivate a record within the custom entity.

The organization wants to track where the lead source came from on the Lead entity as well as have the same option on the account entity in case the user creates the account instead of a lead.

Global Option Set

To create a Global Option set, go to the Customizations, select Option Set from the left navigation and when the Option Sets menu appears select, "New".

Enter in a display name and add the options you wish to have available. In our example the display name will be "Lead Source" and our options will be Web, Walk in, Referral – Customer, Referral –Employee and Trade Show.

To add this option to the form, Select Entity from the Left Navigation and then select which entity you want to add this Global Options set to.

Note: There are multiple ways to create the field and add it to the form. We are going to create the field by adding it through the form design.

Double click on the form you wish to add the field to.

When the form opens, select "New Field" in the lower right hand corner.

Enter in a display name and then select "Option Set" from the Type drop down. Then make sure to select yes to use an existing Option Set. Once that option has been selected, you will receive a drop down list of all of the Global Option sets that are available. Select the appropriate option set. Lastly, you can select a default value if you desire. Once the field has been created, you can now add it to the form.

Custom Entity

To create a custom entity, go to the Customizations, select Entities from the left navigation and when the Entity menu appears select, "New".

Define the Display Name, Plural Name, Ownership, Areas to display and then the options for Entity. You can also define the Primary Field which we will call "Lead Source".

Now that the custom entity has been created, we can add the lookup to the form. We will go through the same steps as described above but this time we will select "Lookup" for the type and the target Record type will be the Lead Source entity we created.

We now can create the values that are needed for the lookup in the Lead Source Entity.

We now want to remove a value from the lookup. To do this simple open the record you wish to no longer be used. The select the "Deactivate" button from the Ribbon entity.

You will receive a confirmation message and select "Ok".

As you can see now the record is now in the inactive view list.

This record is no longer available to be selected when creating or updating a record.

Are you using Global Option Sets in your MSCRM? Let us know if this was a useful hint or have something to add.

Happy CRm'ing!