Tag Archives: CRM

Converting Microsoft Dynamics CRM 4 JavaScript to Microsoft Dynamics CRM 2011 Javascript code converter

I have just seen this javascript converter tool and I thought I’ll let everyone know about it as it could be quite beneficial when upgrading Microsoft Dynamics CRM 4.0 to Microsoft Dynamics CRM 2011 including Javascript upgrade and changes.

This is the link for the tool. I haven’t tested it thoroughly myself yet, so please write your comments and reviews below to let everyone know how good this tool is:
http://bingsoft.wordpress.com/2010/09/09/crm-4-to-crm-2011-javascript-converter-tool/
http://crm2011scriptconvert.codeplex.com/

Hope this helps!

Import & Export Microsoft Dynamics CRM Customizations as XML or as compressed file programatically (dynamically) using CRM API/Web Service

 

It is very common that you would need to import customizations from a file and upload it directly on CRM then publish thes customizations OR the opposite: where you import customisations from Dynamic CRM implementation and export to a file either XML file or a Zip file which you can then archive or add to your source control (TFS or Source Safe). The later is specially common when you need to have a regular backup of your customizations that is stored in TFS or your choses Source control.

To do this, MSDN provides several ways of importing and exporting files (see: http://msdn.microsoft.com/en-us/library/cc151164.aspx)

This is what you can do:

Message name Description
ExportAllXml Export all customizations to an XML file.
ExportCompressedAllXml Export all customizations to an XML file, which is then compressed into a zipped format.
ExportCompressedTranslationsXml Export all translations to an XML file, which is then compressed into a zipped format.
ExportCompressedXml Export the specified customizations to an XML file, which is then compressed into a zipped format.
ExportTranslationsXml Export all translations to an XML file.
ExportXml Export a list of entities to an XML file.
ImportAllXml Import all customizations from an XML file.
ImportCompressedAllXml Import all customizations from an XML file that has been compressed into a zipped format.
ImportCompressedXmlWithProgress Import all customizations with progress logging from an XML file that has been compressed into a zipped format.
ImportTranslationsXmlWithProgress Import all translations from an XML file with progress logging.
ImportXml Import a list of entities from an XML file.
ImportXmlWithProgress Import the specified set of entity customizations from an XML file with progress logging.
PublishAllXml Publish all customizations.
PublishXml Publish a list of entity customizations.

 

Export All XML customizations is usually the most popular one. Here is how you can do it (Code from MSDN):

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
ExportAllXmlRequest request = new ExportAllXmlRequest();

// Execute the request.
ExportAllXmlResponse response = (ExportAllXmlResponse)service.Execute(request);

// Load the results into an XML document.
XmlDocument entityXml = new XmlDocument();
entityXml.LoadXml(response.ExportXml);

 

As for Import All XML customization followed by a publish, here is the code for it:

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// This is a potentially long running operation. The default 90-second
// time-out might be too short.  Set the time-out to be 5 minutes.
// This property takes milliseconds.
service.Timeout = 300 * 1000; 

// Create the request.
ExportAllXmlRequest request = new ExportAllXmlRequest();

// Execute the request.
ExportAllXmlResponse exportResponse = (ExportAllXmlResponse)service.Execute((Request)request);

// Create the request.
ImportAllXmlRequest importRequest = new ImportAllXmlRequest();

// Tell the request where the temporary XML file is located.
importRequest.CustomizationXml = exportResponse.ExportXml;

// Execute the import.
ImportAllXmlResponse importResponse = (ImportAllXmlResponse)service.Execute(importRequest);

Finally to publish your customizations, this is what you need to do:

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
PublishAllXmlRequest request = new PublishAllXmlRequest();

// Execute the request.
PublishAllXmlResponse response = (PublishAllXmlResponse)service.Execute(request);

Creating, consuming and using Microsoft Dynamics CRM 4.0 Service, Using CRM API and CRM SDK to access CRM database via the webservice

  

Creating, consuming and using Microsoft Dynamics CRM 4.0 Service, Using CRM API and CRM SDK to access CRM database via the webservice. Custom .NET code to access CRM, create, update (edit), insert, delete, retrieve (return) and retrievemultiple records for system entities and custom entities using both entity objects and dynamic entities. 

This post is a collection of the main methods that you would frequently use in your .NET code (Plugin, Website) that is accessing a dynamics CRM 4.0 system and consuming its CRM services. 

The CrmService Web service provides a set of methods used to perform the most common operations on system and custom entities. 

This collection mainly comes from sevaral pages on MSDN. I just thought it will be useful to have them all together if we need one or more of them. 

  

The following code shows how to set up the Web service, and how to use the Create and Retrieve methods. 

  

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create an account entity and assign data to some attributes.
account newAccount = new account();
newAccount.name = "Greg Bike Store";
newAccount.accountnumber = "123456";
newAccount.address1_postalcode = "98052";
newAccount.address1_city = "Redmond";
 
// Call the Create method to create an account.
Guid accountId = service.Create(newAccount);
 
Guid contactId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");
 
// Call the Retrieve method to retrieve an existing contact.
ColumnSet myColumnSet = new ColumnSet();
myColumnSet.Attributes = new string[] { "firstname" };
contact myContact = (contact) service.Retrieve ("contact", contactId, myColumnSet)

  

 

 

—————————- 

The following example demonstrates the use of the Create method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 
// You can use enums.cs from the SDK\Helpers folder to get the enumeration 
//   for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the contact object.
contact contact = new contact();
 
// Create the properties for the contact object.
contact.firstname = "Jesper";
contact.lastname = "Aaberg";
contact.address1_line1 = "23 Market St.";
contact.address1_city = "Sammamish";
contact.address1_stateorprovince = "MT";
contact.address1_postalcode = "99999";
contact.donotbulkemail = new CrmBoolean();
contact.donotbulkemail.Value = true;
 
// Create the contact in Microsoft Dynamics CRM.
Guid contactGuid = service.Create(contact);

  

———————————- 

  

The following example demonstrates the use of the Retrieve method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the column set object that indicates the properties to be retrieved.
ColumnSet cols = new ColumnSet();
 
// Set the properties of the column set.
cols.Attributes = new string [] {"fullname"};
 
// contactGuid is the GUID of the record being retrieved.
Guid contactGuid = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Retrieve the contact.
// The EntityName indicates the EntityType of the object being retrieved.
contact contact = (contact)service.Retrieve(EntityName.contact.ToString(), 
                                             contactGuid, cols);

  

  

—————————- 

  

The following example demonstrates the use of the RetrieveMultiple method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the ColumnSet that indicates the properties to be retrieved.
ColumnSet cols = new ColumnSet();
 
// Set the properties of the ColumnSet.
cols.Attributes = new string [] {"fullname", "contactid"};
 
// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();
 
// Set the condition for the retrieval to be when the 
//    contact's address' city is Sammamish.
condition.AttributeName = "address1_city";
condition.Operator = ConditionOperator.Like;
condition.Values = new string [] {"Sammamish"};
 
// Create the FilterExpression.
FilterExpression filter = new FilterExpression();
 
// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions = new ConditionExpression[] {condition};
 
// Create the QueryExpression object.
QueryExpression query = new QueryExpression();
 
// Set the properties of the QueryExpression object.
query.EntityName = EntityName.contact.ToString();
query.ColumnSet = cols;
query.Criteria = filter;
 
// Retrieve the contacts.
BusinessEntityCollection contacts = service.RetrieveMultiple(query);

  

—————————- 

  

  

The following example demonstrates the use of the Update method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the contact object.
contact contact = new contact();
 
// Set the contact object properties to be updated.
contact.address1_line1 = "34 Market St.";
 
// The contactid is a key that references the ID of the contact to be updated.
contact.contactid = new Key();
// The contactid.Value is the GUID of the record to be changed.
contact.contactid.Value = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Update the contact.
service.Update(contact);

  

—————————- 

  

The following example demonstrates the use of the Delete method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// contactGuid is the GUID of the record being deleted.
Guid contactGuid = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Delete the contact.
// The EntityName indicates the EntityType of the object being deleted.
service.Delete(EntityName.contact.ToString(), contactGuid);

  

—————————- 

  

For Dynamic Entities: The following sample shows how to create a new entity instance by calling the CreateEntity method followed by the AddObject method. 

  

var contact = crm.CreateEntity("contact");
 
// Set the string properties.
contact.SetPropertyValue("firstname", "Allison");
contact.SetPropertyValue("lastname", "Brown");
contact.SetPropertyValue("emailaddress1", "allison.brown@contoso.com");
 
// Setting an explicit ID value is optional, it can be left unassigned, 
//    but here it is being explicitly assigned.
var id = Guid.NewGuid();
contact.SetPropertyValue("contactid", id);
 
// Pass the entity name of the entity being created as the first parameter.
crm.AddObject("contact", contact);
crm.SaveChanges();
 
// The ID value can be retrieved after you have called the SaveChanges method.
var id2 = contact.GetPropertyValue<Guid>("contactid");

  

  

  

These methods have been collected from MSDN mainly from these two locations:  http://msdn.microsoft.com/en-us/library/cc151016.aspx and http://msdn.microsoft.com/en-us/library/ff681571.aspx  

  

  

Get Current User Security Roles in Microsoft Dynamics CRM 4.0 on client side using JavaScript calls to CRM Service & API

In Microsoft Dynamics CRM 4.0, it is quite common that you want to call the CRM service from client side: i.e. Call the CRM service using JavaScript code that is located on the OnLoad, OnSave or OnChange events on a Dynamics CRM entity or field event.

The most common call is the call to CRM service to determine what roles the current user has.

The following function returns all roles of a specific user by creating a SOAP message request to the CRM Service:

//*********************
function GetCurrentUserRoles()
{
 var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
 " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>role</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>" +
 "";

 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
 xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
 xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
 xmlHttpRequest.send(xml);

 var resultXml = xmlHttpRequest.responseXML;
 return(resultXml);
}
//*********************

 The following function checks if the specified user has a specified user role:

//*********************
function UserHasRole(roleName) {
    //get Current User Roles, oXml is an object
    var oXml = GetCurrentUserRoles();
    if (oXml != null) {
        //select the node text
        var roles = oXml.selectNodes("//BusinessEntity/q1:name");
        if (roles != null) {
            for (i = 0; i < roles.length; i++) {
                if (roles[i].text == roleName) {
                    //return true if user has this role
                    return true;
                }
            }
        }
    }
    //otherwise return false
    return false;
}
//*********************

The following code block uses the above function to do some logic based on user’s security roles:

if(UserHasRole("System Administrator"))
{
  //do something
}
else
{
   //do something else
}

Embedding ISV web applications in Microsoft Dynamics CRM 4.0 through SiteMap (not as an IFrame) via a left navigation link. Application & link Access restriction through Site Map

There are (at least) two standard ways of implementing an external ISV web application (website, html, .NET, etc..) inside your dynamics CRM application.

The first way is by creating an IFrame inside the form of an entity. This is quite straight forward and can be achieved from the entity customisation section in CRM settings.

The second option is to create a link in the left navigation of your Microsoft Dynamics CRM 4.0 solution. This link can then point to your ISV webpage (aspx page for example) and you will have your web page implemented and embedded inside CRM. If you also do the application css (stylesheet file)  to be same colours and similar styles as CRM colours and styles, your application will be presented nicely inside CRM as if it is part of CRM. The permission and restriction of access to this web application and its left navigation link is also controlled to show/hide the applications to users.

This post is discussing the second option.

Embedding a webpage or web application in CRM and having  CRM’s left navigation linked to it can be done by editing the sitemap customisation file (xml). This left nav link can be shown or hidden to users based on their security roles and this is also controlled in the site map file. If the link is hidden, then obviously the web application will not be accessible and cannot be retrieved by unauthorised users.

The following is an example of a sitemap file that displays two links to two applications on the top of the left navigation menu of CRM 4.0. The privilage for accessing each link is also set in the following example:

<SiteMap>
    <SiteMap>
      <Area Id="Workplace" ResourceId="Area_Workplace" ShowGroups="true"
Icon="/_imgs/workplace_24x24.gif" DescriptionResourceId="Workplace_Description">
        <Group Id="MyWork" ResourceId="Group_MyWork" 
DescriptionResourceId="My_Work_Description">
          <SubArea Id="MyWebApplication" Icon="/_imgs/ico_18_servicecal.gif" 
Url="../../ISV/MyWebApplication/WebPage.aspx" AvailableOffline="false">
            <Titles>
              <Title LCID="1033" Title="My Web Application ONE" />
            </Titles>
            <Descriptions>
              <Description LCID="1033" Description="My Web Application ONE" />
            </Descriptions>
<!-- this is where you control displaying the 1st link-->
<!-- if the user has read and write access to entity Kbarticle (for ex)-->
<!-- then they should be able to view this link. Otherwise, its hidden-->
            <Privilege Entity="kbarticle" Privilege="Read,Write" /> 
          </SubArea><!--another example follows: -->
          <SubArea Id="WebPage2" Icon="/_imgs/ico_18_servicecal.gif"  
Url="../../ISV/WebApplication2/index.htm" AvailableOffline="false">
            <Titles>
              <Title LCID="1033" Title="Web Page 2" />
            </Titles>
            <Descriptions> 
<!-- if the user has create access to entity Kbarticle (for ex)-->
<!-- then they should be able to view this link. Otherwise, its hidden-->
              <Description LCID="1033" Description="Web Page 2" />
            </Descriptions>
            <Privilege Entity="kbarticle" Privilege="Create" />
          </SubArea>
<!-- The following is the standard activity left link for CRM-->
          <SubArea Id="nav_activities" Entity="activitypointer"  
DescriptionResourceId="Activities_SubArea_Description"  
Url="/Workplace/home_activities.aspx" />

This is how you can get site map to control your left navigation buttons and get them to link to ISV applications. Please mind that you might need to change the relative location of your application in the URL parameter.

Hope this helps.

 

Microsoft Dynamics CRM 4 field level validation using javascript regular expression on client side handling the onChange event to validate and check the value and text of a CRM 4.0 field

Please note that this post is aimed as showing how to use javascript regular expression field level validation in Microsoft Dynamics CRM. The post does not focus on the many ways of getting a regular expression. The example regular expression below is used for explanation only.

If you want to create validation at field level in Microsoft Dynamics CRM 4 to check the input value and text of a CRM field in an entity form, you can do this using regular expressions written in javascript code that handles the on change (onChange) event of this field at client side.

Below is an example of a regular expression but you might want to use your own regex value or search online for almost unlimited number of regular expressions that do just about anything.

For example, if you want to validate a CRM 4 field so that only a 4 digit year value starting from year 1980 is entered in the field text box, follow the following steps:

- Open the entity customisation form
- select the field you want to validate using javascript regular expression.
- Click on field properties, events tab and then open the onChange event.
- In the onChange event type the following javascript code (script) to handle the event and implement the field level validation:

//-----------------------------
//Regular expression ensuring a 4 digit year value is input starting from year 1980.
var reDate =/^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$/
//Check if the input value satisfies the regular expression condition
if (document.crmForm.all.new_yearfieldname.value.search(reDate)==-1)
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------

Another way of doing this is as follows;

//-----------------------------
var regexS = "^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$"; 
var regex = new RegExp( regexS ); 
var results = regex.exec( crmForm.all.new_yearfieldname.value);
if( results == null )   
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------------------

Hope this helps.

Click through to CRM records from SSRS custom report for Microsfot Dynamics CRM 4. Linking information on SQL Reporting Services custom CRM reports to Dynamics CRM 4 records and opening them up from within the report.

If you are writing a custom report – SQL Server Reporting Services (SSRS) report for Microsoft Dynamics CRM 4, you might want to add the functionality (sql expression) to click through to a record. This can be applied to some or all information shown on the report, so that if you click on the information text box, you open up the corresponding CRM record in a new window such as: click on sub-account in the sub-accounts list to open this sub-account CRM record, or the same for contact, opportunities and so on.

To do this, right click on the text box in where you will be putting the expression and the value to be clicked on, and click on Texbox properties. On there click on Actions on the left, select last option “Go to URL” and in the expression box type the following query expression

=IIF(IsNothing(Parameters!CRM_URL.Value),system.dbnull.value,Parameters!CRM_URL.Value & "?ID={"&Fields!Accountid.Value.ToString()&"}&OTC=1")
/*Replace "&Fields!Accountid" with the ID of the corresponding record */
/*you want to be open, so contactid, opportunityid or any other custom entity id field*/
/*Also replace OTC value above with the Entity Object type Code (OTC) value*/

You can get any entities OTC value from the “EntityView” view or for the full list of all system entities type codes, read this MSDN article: http://msdn.microsoft.com/en-us/library/bb887791.aspx. Obviously you will need to get the OTC value for your custom entities from the “EntityView” view from your Dynamics CRM database. You can use a query similar to the following:

select entitytypecode from entityview where entityname = 'account'

This sql expression can work with any entity either system (cusomisable) or custom entity.

Hide tab in any entity form in Microsoft Dynamics CRM 4 using Javascript in onLoad event of the form.

In many cases, you might want to remove one of the tabs of an entity form in Microsoft Dynamics CRM 4. This can be specifically helpful in two cases:

1- If you want to hide and show tabs depending on a picklist value selection such as contact type: Hide Work details if contact is of type internal contact for example

2- If you want to hide the Administration and Notes tab from an entity form while these tabs are locked and cannot be removed from the entity form.

To hide a tab in an entity form, you can use the following Javascript sample script:

//---------------------------Hide a tab by passing tab name to the function
HideTab('Administration');
//replace "Administration" with your tab name
function HideTab (tabText)
{
 var tab = FindTab(tabText);
 if (tab)
 {
  tab.style.display = "none";
 }
}
function FindTab(tabText)
{
 var tabBar = document.getElementById("crmTabBar");
 if (tabBar)
 {
  var tabs = tabBar.childNodes;  

  for (var i = 0, len = tabs.length; i < len; i++)
  {
   var currentTab = tabs[i];
   if (currentTab.innerText === tabText)
   {
    return currentTab;
   }
  }
 }
}
//-----------------end of script--------

Maxjerin has added a new code suggestion. Maxjerin’s code hides a tab based on the onChange event of a field on the form. If the primary contact “name” field is maxjerin, the tab is displayed. Otherwise the tab is hidden.

I have updated the post to include Maxjerin’s code – Thanks Maxjerin:

Here is the code that I used to HIDE/UNHIDE a tab when I wanted to show it for only one particular user and hide for others. The code includes some alert messages just for debugging purpose which you might find useful to understand the code. You may remove them once done.

This section goes into the onChange section of the Primary Contact lookup field

if (crmForm.all.primarycontactid.DataValue == null )
{
var strTabStatus = TabStatus(‘Profile’);
if ( strTabStatus == ”)
{
alert(“Primary Contact none, hiding the tab”);
HideTab(‘Profile’);
}
}
else if (crmForm.all.primarycontactid.DataValue[0].name == ‘maxjerin’)
{
alert(“Primary Contact p f, unhiding the tab”);
UnHideTab(‘Profile’);
//replace “Administration” with your tab name
}
else if (crmForm.all.primarycontactid.DataValue[0].name != ‘maxjerin’)
{
var strTabStatus = TabStatus(‘Profile’);
if (strTabStatus == ” )
{
alert(“Primary Contact other than maxjerin, Hiding the tab”);
HideTab(‘Profile’);
}
}
function HideTab (tabText)
{
var tab = FindTab(tabText);
if (tab)
{
tab.style.display = “none”;
}
}
function UnHideTab (tabText)
{
var tab = FindTab(tabText);
if (tab)
{
tab.style.display = “”;
}
}
function FindTab(tabText)
{
var tabBar = document.getElementById(“crmTabBar”);
if (tabBar)
{
var tabs = tabBar.childNodes;
for (var i = 0, len = tabs.length; i < len; i++)
{
var currentTab = tabs[i];
if (currentTab.innerText === tabText)
{
return currentTab;
}
}
}
}
function TabStatus(tabText)
{
var tabBar = document.getElementById(“crmTabBar”);
if (tabBar)
{
var tabs = tabBar.childNodes;
for (var i = 0, len = tabs.length; i < len; i++)
{
var currentTab = tabs[i];
if (currentTab.innerText === tabText)
{
if (currentTab.style.display == ‘none’)
{
alert(“tab already hidden, TAB NAME: ” + currentTab.innerText );
return “none”;
}
else
{
alert(“tab is visible, TAB NAME: ” + currentTab.innerText );
return “”;
}
}
}
}
}
//-----------------------------------------------------------------------
Please comment below if you have any feedback or anything to add.
Thanks

Return and display picklist value (display value) in custom sql report reporting services report in Microsoft Dynamics CRM 4 entity attribute and StringMap picklist values table

Normally, you should be able to get the picklist display value and picklist item id in the filtered view of any entity. In some cases, you may need to work with StringMap table directly to get the picklist values for a specific field of a given entity. This could be the case if you are not using the filtered view for some reason or if you want to write a report based on the table or the non-filtered view, the following post is providng the query (queries) needed to do so.

To get the display value of any picklist, you need to use the StringMap table. If you are writing a custom ssrs (SQL Server Reporting Services) report for Dynamics CRM 4, you usually need to return the picklist display value not the picklist item id.

For example: in the opportunity entity, you have a picklist attribute “Rating” (attribute name opportunityratingcode). If you are writing a custom SQL report to add to CRM and you want to display the values of the attribute, you will find that the display value of the picklist is not stored in the filtered view of Opportunity (FilteredOpportunity). To get the display value of any picklist, you need to use the StringMap table.

There many ways to get the information from the StringMap table, I will mention two ways here:

1) using Inner Join (simple - one picklist only)
This way, you just simply join the two tables: your entity filteredview and the StringMap table
/* the query uses out of the box attributes, so should run successfully on all CRM organisations*/
SELECT opp.name, opp.estimatedvalue_base, opp.closeprobability, StringMap.Value
FROM Opportunity as Opp INNER JOIN
  StringMap ON Opp.opportunityratingcode = StringMap.AttributeValue
WHERE (StringMap.ObjectTypeCode = 3) AND (StringMap.AttributeName = N'opportunityratingcode')
AND (opp.accountid = 'input your accoung GUID here'

This query will return list of all Opportunities for the specified account display the picklist display value rather than the id.

2) using Temp table (my prefered way for multiple picklists)

This query is longer and uses/declares temp tables but it is the simplest way in case you have several picklists and you want to return the display value of multiple picklists. You just create several temp tables just like @TempSM, where each temp table returns the list of display values for each picklist and then join them together.

1 Picklist query:
/* the query uses out of the box attributes, so should run successfully on all CRM organisations*/
Declare @TempOpp table(OpportunityID uniqueidentifier, OpportunityName nVarchar(max),
Estimatedvalue float, Probability float, Rating nVarchar(max))
Insert into @TempOpp
select opp.opportunityid,opp.name ,
opp.estimatedvalue_base,
opp.closeprobability,
opp.OpportunityRatingCode
From Opportunity opp
where opp.accountid = '97F97A5A-2622-DF11-A1C3-005056BA6B8A'
Declare @TempSM table(AttributeValue nVarchar(max), Value nVarchar(max))
Insert into @TempSM
select AttributeValue, Value
from StringMap
WHERE (StringMap.ObjectTypeCode = 3) AND
(StringMap.AttributeName = N'opportunityratingcode' )
select t1.OpportunityName, t1.Estimatedvalue, t1.Probability, t2.Value as RatingDisplayValue
from @TempOpp as t1 left outer JOIN @TempSM as t2 ON
(t1.Rating = t2.AttributeValue)

This query will return list of all Opportunities for the specified account display the picklist display value rather than the id.

2 Picklists query:
------------------
/* the query uses out of the box attributes, so should run successfully on all CRM organisations*/
Declare @TempOpp1 table(OpportunityID uniqueidentifier, OpportunityName nVarchar(max),
Estimatedvalue float, Probability float, Rating nVarchar(max), Priority nVarchar(max))
Insert into @TempOpp1
select opp.opportunityid,opp.name ,
opp.estimatedvalue_base,
opp.closeprobability,
opp.OpportunityRatingCode,
opp.PriorityCode
From Opportunity opp
where opp.accountid = '97F97A5A-2622-DF11-A1C3-005056BA6B8A'
/* Now we have @TempOpp1 with list of all opportunities for the specified account but with ID for picklist value not display names*/
/*Then we declare a temp table for Rating picklist*/
Declare @TempSM table(AttributeValue nVarchar(max), Value nVarchar(max))
Insert into @TempSM
select AttributeValue, Value
from StringMap
WHERE (StringMap.ObjectTypeCode = 3) AND
(StringMap.AttributeName = N'opportunityratingcode' )
Declare @TempOpp2 table(OpportunityID uniqueidentifier, OpportunityName nVarchar(max),
Estimatedvalue float, Probability float, Rating nVarchar(max), Priority nVarchar(max))
Insert into @TempOpp2
select t1.OpportunityID, t1.OpportunityName, t1.Estimatedvalue, t1.Probability,
t2.Value as RatingDisplayValue,t1.Priority as Priority
from @TempOpp1 as t1 left outer JOIN @TempSM as t2 ON
(t1.Rating = t2.AttributeValue)
/*tempopp2 now has opportunities with the rating display value*/
/*Now creating a temp table for Priority picklist*/
Declare @TempSM1 table(AttributeValue nVarchar(max), Value nVarchar(max))
Insert into @TempSM1
select AttributeValue, Value
from StringMap
WHERE (StringMap.ObjectTypeCode = 3) AND
(StringMap.AttributeName = N'PriorityCode' )
select t1.OpportunityID, t1.OpportunityName, t1.Estimatedvalue, t1.Probability,
t1.Rating as RatingDisplayValue,t2.Value as Priority
from @TempOpp2 as t1 left outer JOIN @TempSM1 as t2 ON
(t1.Rating = t2.AttributeValue)

--------------------------------------------

and so on. You create temp table for each picklist, join it with opportunity temp table and then carry on.

Note: This is one way of doing this. There are obviously many other shorter ways of doing this. I personally prefer temp tables a lot because although longer, they are simpler and easier to use. They also bypass any issues with null values in the right table of the join.

Not related Note: Always use filtered views when writing custom SQL reports on SSRS for CRM as they comply with CRM security.

Hide, Display, Resize and Rename left navigation links, CRM fields and attributes using Javascript for Microsoft Dyanmics CRM 4.

Scripts for Resizing, Hiding and renaming left navigation links, fields and attributes in Microsoft Dynamics CRM 4 using Javascript. This post is just a collection of some Javascript code for various common scripts that is frequently used in CRM form events, CRM entity events, etc. These script blocks can be used in OnLoad, OnSave events for CRM forms and OnChange events for CRM fields.

//------- Resize CRM form in the onload event
window.resizeTo(screen.availWidth * 0.85, screen.availHeight * 0.85);
//-------Rename left menu link / Left Navigation. Example: Contacts
var navItem = document.getElementById(’navContacts’);
navItem.innerHTML = navItem.innerHTML.replace(’>Contacts’,'>Students’);
//------Hide left menu link / Navigation. Example: Workflow
var navLeftItem = document.getElementById(’navAsyncOperations’);
navLeftItem.style.display = ‘none’;
//-----Hide Left navigation menu item link of a CRM form based on
// a value in a picklist on the same form.
//Get contacts left navigation menu item element.
var navLeftItem = document.getElementById(’navContacts’);
//if picklist (customer type code) value is equal to 1 (1st item in picklist) then
//hide left menu item (contacts link is used as an example), otherwise, show it.
if(crmForm.all.customertypecode.DataValue == 1)
{
 navLeftItem.style.display = ‘none’;
}
else
{
 navLeftItem.style.display = ‘inline’;
}
 //-----Hide a CRM field on a form. example: the "name" field.
crmForm.all.name_c.style.display = 'inline';
crmForm.all.name_d.style.display = 'inline';
//-----Hide a CRM field on a form (example: the "name" field)
//based on the selected value in a picklist
if(crmForm.all.customertypecode.DataValue == 1)
{
         crmForm.all.name_c.style.display = 'inline';
         crmForm.all.name_d.style.display = 'inline';
}
else
{
         crmForm.all.name_c.style.display = 'none';
         crmForm.all.name_d.style.display = 'none';
}  ////Add this code to the OnLoad event of the form and
////to the on change event of the picklist attribute (field) as well
//---------Function to hide CRM field in a form. 
//Function accept fieldname as a parameter and
//boolean parameter to remove (hide) entire row on form
HideField('name'); //replace "name" with your field/attribute name
 
function HideField( fieldName, removeEntireRow )
{
 // Always hide the elements, even if we will be hiding the whole row.
 // This allows us to show another field in this row later without this
 // one showing up.
 var elem = crmForm.all[fieldName + "_c"];
 if( elem != null ) elem.style.display = "none";
 elem = crmForm.all[fieldName + "_d"];
 if( elem != null ) elem.style.display = "none";     
 
 if (removeEntireRow)
 {
  var elem = crmForm.all[fieldName + "_d"];
  if( elem != null ) elem.parentElement.style.display = "none";
 }
}

 This post was written quickly from memory and some code blocks here and there, so you might find some minor spelling mistakes. Please comment below if you find any issues with the script blocks or if you want me to extend this post to include additional script.