Showing related entity information in Header as Hyperlink – CRM 2011

We recently had requirement to show the Case Information in one of its related (related) entity’s header. The information should appear as a hyperlink so that users can open the case directly from that entity’s form.

Case entity was having 1-n relationship with this other entity say Entity A and Entity A was related 1-n with Entity B. In Entity A we had moved the lookup of Case in the header. So from Entity A’s form user could click the lookup in header (as lookup appeared as hyperlink in Header) and open the Case.

Now they wanted the similar kind of functionality in Entity B. However as Entity B was not directly related to Case entity it had no lookup or any other field having Case information in it.

So this is what we did :-

  1. Created a new HTML Web Resource.
  2. Added an anchor tag in it.
  3. Used JavaScript to get the Case Information from the lookup of the Entity A in the form.
  4. Dynamically setting the href and innerHTML of the anchor tag so that it provides case information and link clicking on which should open the case record.
  5. Add the Web Resource in the header of the Entity B form.
  6. As we were using JSON here, added the JSON library in the form load.

    Case Information in the header and the hyperlink:-

Sample Code of the HTML Web Resource:-


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Case Information</title>
 <script src="ClientGlobalContext.js.aspx"></script>
 <script type="text/javascript" src="new_json2"></script>
 <style type="text/css">
 .ms-crm-Field-Normal
 {
 font-family: Segoe UI, Tahoma, Arial;
 font-size: 13px;
 position:absolute;
 top:0px;
 text-align: left;
 }


 </style>
 <meta charset="utf-8">
</head>
<body style="background-color: #f7fbff; margin: 10px" onload="GetCaseInformation()"
 contenteditable="true">
 <a id="anchorCase" href="#" target="_blank" class="ms-crm-Field-Normal"></a>
 <script>

var FORM_TYPE_UPDATE = 2;
 var FORM_TYPE_READ_ONLY = 3;
 var FORM_TYPE_DISABLED = 4;


 var ODataPath;
 var serverUrl;
 var entityName = "";
 var id = "";
 var entity;

function GetCaseInformation() {
 init();
 }

function init() {


 serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
 ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
 if (parent.Xrm.Page.ui.getFormType() == FORM_TYPE_UPDATE ||
 parent.Xrm.Page.ui.getFormType() == FORM_TYPE_READ_ONLY ||
 parent.Xrm.Page.ui.getFormType() == FORM_TYPE_DISABLED) {

// get the lookup control and its guid and entity type
 var value = parent.Xrm.Page.ui.controls.get('new_casemedicalconditionid').getAttribute().getValue();

if (value != null) {
 id = value[0].id.replace('{', '').replace('}', '');
 entityName = value[0].entityType;
 }
 }
 // get the case information
 retrieveRecord(id);
 }

function retrieveRecord(Id) {
 var retrieveReq = new XMLHttpRequest();
 var url = ODataPath + "/" + entityName + "Set(guid'" + Id + "')";

retrieveReq.open("GET", ODataPath + "/" + entityName + "Set(guid'" + Id + "')", true);
 retrieveReq.setRequestHeader("Accept", "application/json");
 retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 retrieveReq.onreadystatechange = function () {
 retrieveReqCallBack(this);
 };
 retrieveReq.send();
 }

function retrieveReqCallBack(retrieveReq) {


 if (retrieveReq.readyState == 4 /* complete */) {
 if (retrieveReq.status == 200) {
 //Success

 entity = JSON.parse(retrieveReq.responseText).d;
 if (entity.new_CaseId != null) {
 var caseGuid = entity.new_CaseId.Id;
 var caseName = entity.new_CaseId.Name;
 var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
 if (document.getElementById('anchorCase').innerHTML == "") {
 document.getElementById('anchorCase').innerHTML = caseName;
 document.getElementById('anchorCase').href = serverUrl + "/CS/cases/edit.aspx?id={" + caseGuid + "}";
 }
 }
 }
 }
 }

</script>
</body>
</html>


Bye.

Using Deep Insert (creating multiple new records in the same operation) in Silverlight (CRM 2011)

Hi,

Sharing a basic example using which we can create Parent entity and the related entity records in the same operation\

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

Check out this helpful post

http://inogic.blogspot.com/2011/12/odata-properties-and-methods-explored.html


public MainPage()
 {
 InitializeComponent();
 }

GGContext context;

private void UserControl_Loaded(object sender, RoutedEventArgs e)
 {
 var orgServiceUrl = "http://servername/orgname/XRMServices/2011/OrganizationData.svc";

 // initialize the context
 context = new GGContext(new Uri(orgServiceUrl));

// using client http stack
 context.HttpStack = System.Data.Services.Client.HttpStack.ClientHttp;
 context.UseDefaultCredentials = false;
 context.Credentials = new NetworkCredential("administrator", "password", "domain");
 // create contact record
 Contact contact = new Contact();
 contact.LastName = "Rana";
 contact.FirstName = "Nisha";

 // create two tasks and one email activity
 var myTask1 = new Task();
 myTask1.Subject = "Task1 created at " + DateTime.Now.ToLongTimeString();
 var myTask2 = new Task();
 myTask2.Subject = "Task2 created at " + DateTime.Now.ToLongTimeString();
 var myEmail = new Email();
 myEmail.Subject = "Email created at " + DateTime.Now.ToLongTimeString();

// add the tasks and email to their respective set
 context.AddToTaskSet(myTask1);
 context.AddToTaskSet(myTask2);
 context.AddToEmailSet(myEmail);

// add contact to be created to the contact set
 context.AddToContactSet(contact);

// add the related records
 contact.Contact_Tasks.Add(myTask1);
 contact.Contact_Tasks.Add(myTask2);
 contact.Contact_Emails.Add(myEmail);

 // add the link
 // http://inogic.blogspot.com/2011/12/odata-properties-and-methods-explored.html
 context.AddLink(contact, "Contact_Tasks", myTask1);
 context.AddLink(contact, "Contact_Tasks", myTask2);
 context.AddLink(contact, "Contact_Emails", myEmail);

context.BeginSaveChanges(CreateContactHandler, contact);
 }
 private void CreateContactHandler(IAsyncResult result)
 {
 // in the call back method call the EndSaveChanges method
 // it returns DataServiceResponse object.
 // we can get the error information from this object in case an operation fails
 context.EndSaveChanges(result);
 // id of the created contact record
 Guid createdContactGuid = ((Contact)result.AsyncState).ContactId;
 }

Hope it helps

Create Retrieve Update and Delete using oData (Rest endpoint) in Silverlight (CRM 2011)

Hi,

Sharing a basic example that performs CRUD operation using Rest endpoint in Silverlight.

namespace odataSilverlight
{
 public partial class MainPage : UserControl
 {
 public MainPage()
 {
 InitializeComponent();
 }

GGContext context;
 private void UserControl_Loaded(object sender, RoutedEventArgs e)
 {
 var orgServiceUrl = "http://r78-7-amscrm/GG/XRMServices/2011/OrganizationData.svc";

 // initialize the context
 context = new GGContext(new Uri(orgServiceUrl));

// using client http stack
 context.HttpStack = System.Data.Services.Client.HttpStack.ClientHttp;
 context.UseDefaultCredentials = false;
 context.Credentials = new NetworkCredential("administrator", "Secure*8", "AMS");
 // create contact record
 Contact contact = new Contact();
 contact.LastName = "Rana";
 contact.FirstName = "Akshaj";

// add the new contact to the contact set
 context.AddToContactSet(contact);
 // call BeginSaveChanges method and specify the callback method and the contact object
 context.BeginSaveChanges(CreateContactHandler, contact);

}
 private void CreateContactHandler(IAsyncResult result)
 {
 // in the call back method call the EndSaveChanges method
 // it returns DataServiceResponse object.
 // we can get the error information from this object in case an operation fails
 context.EndSaveChanges(result);
 // id of the created contact record
 Guid createdContactGuid = ((Contact)result.AsyncState).ContactId;

// Retrieve the created contact record
 DataServiceQuery<Contact> queryContact = (DataServiceQuery<Contact>)
 context.ContactSet.
 AddQueryOption("$filter", "ContactId eq guid'" + createdContactGuid + "'");
 queryContact.BeginExecute(RetrieveContactHandler, queryContact);

}

private void RetrieveContactHandler(IAsyncResult result)
 {
 DataServiceQuery<Contact> contacts = result.AsyncState as DataServiceQuery<Contact>;
 Contact retrievedContact = new DataServiceCollection<Contact>(contacts.EndExecute(result)).First<Contact>();

// Update the retrieved contact record's first name
 retrievedContact.FirstName = "Mickey";

context.UpdateObject(retrievedContact);
 context.BeginSaveChanges(UpdateContactHandler, retrievedContact);

}

private void UpdateContactHandler(IAsyncResult result)
 {
 context.EndSaveChanges(result);
 Contact contact = (Contact)result.AsyncState;

// Delete the updated contact record
 context.DeleteObject(contact);
 context.BeginSaveChanges(DeleteContactHandler, contact);
 }
 private void DeleteContactHandler(IAsyncResult result)
 {
 context.EndSaveChanges(result);
 }
 }
}

Hope it helps

Using AddQueryOption to write oData query in Silverlight (CRM 2011)

Hi,

The easiest way to write oData query is to make use of this wonderful tool developed by Rhett Clinton:-

http://crm2011odatatool.codeplex.com/

The query generated by tool can be used in Jscript. They can also be used to write DataServiceQuery in Silverlight project using AddQueryOption.

Here are few examples: –

  • The query to get the subject and city of all the lead records

http://servername/orgName/xrmservices/2011/OrganizationData.svc/LeadSet?

$select=Address1_City,Subject

Now while writing DataServiceQuery simple set the first parameter of AddQueryOption as $select and the value part of it as the second parameter.

var queryLead = context.LeadSet.AddQueryOption("$select", "Address1_City,Subject") as DataServiceQuery<Lead>;


  • The query to get the subject and city of all the lead records where subject contains string ‘test’

http://sname/orgname/xrmservices/2011/OrganizationData.svc/LeadSet?

$select=Address1_City,FullName&$filter=substringof(‘test’,Subject)

Here we will add two query option one for select and other for filter criteria

var queryLead = context.LeadSet
.AddQueryOption("$select", "Address1_City,Subject")
.AddQueryOption("$filter", "substringof('test',Subject)")
as DataServiceQuery<Lead>;


  • The query to get the subject of all the lead records along with owner’s Business Unit Name (i.e. related entity)

http://sname/orgname/xrmservices/2011/OrganizationData.svc/LeadSet?

$select=Subject,lead_owning_user/BusinessUnitId&$expand=lead_owning_user

Here we are making use of expand to get the data from the related entity

var queryLead = context.LeadSet
.AddQueryOption("$select", "Subject,lead_owning_user/BusinessUnitId")
.AddQueryOption("$expand", "lead_owning_user")
as DataServiceQuery<Lead>;

To run the query and loop through the records returned we can make use of following code:-

DataServiceCollection<Lead> leads = new DataServiceCollection<Lead>();
leads.LoadCompleted += (s, ea) =>
{

foreach (Lead lead in leads)
{
MessageBox.Show(lead.Subject);
MessageBox.Show(lead.lead_owning_user.BusinessUnitId.Name);
}

};

leads.LoadAsync(queryLead);

Hope this helps.

Sample code to parse JSON Date Format

Hi,

Just sharing a sample code to parse JSON Date Format (e.g. “\/Date(628318530718)\/”) to Date.


entity = JSON.parse(retrieveReq.responseText).d;

if (entity['BirthDate'] != null) {

var jdate = parseJsonDate(entity['BirthDate']);
 var year = jdate.getFullYear();
 var month = jdate.getMonth() + 1 < 10 ? '0' + (jdate.getMonth() + 1) : (jdate.getMonth() + 1);
 var date = jdate.getDate() < 10 ? '0' + jdate.getDate() : jdate.getDate();
 var dateString = month + '/' + date + '/' + year;

 alert(dateString);
 }

function parseJsonDate(jsonDate) {
 var offset = new Date().getTimezoneOffset() * 60000;
 var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

if (parts[2] == undefined)
 parts[2] = 0;

if (parts[3] == undefined)
 parts[3] = 0;

return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
 }

}

Bye.

Using Client HTTP Stack with oData in Silverlight (CRM 2011)

Hi,

Just sharing a simple example that uses Client HTTP Stack while developing Silverlight web resource.

The good thing with this is that we don’t have to upload and publish the web resource for every change. However if the Siliverlight component is running in the context of the form and interacting with it then in that case we will have to upload and publish it.

Steps : –

Create a Silverlight application and add service reference to the oData service of CRM 2011.

Go to Settings |Customizations | Developer Resources

Get the url of the OrganizationData service

Add Service Reference to the URL

The context would be named as OrganizationNameContext.

Now in the MainPage.xaml set the url of the OrganizationData and Set up the context in the following manner.

 public partial class MainPage : UserControl
 {

private GGContext context;
 private String orgDataServerUrl;

public MainPage()
 {
 InitializeComponent();

// set the server url
 orgDataServerUrl = "http://server:port/GG/XRMServices/2011/OrganizationData.svc";

// set the context
 context = new GGContext(new Uri(orgDataServerUrl));

// set up the Client Http Stack
 context.HttpStack = System.Data.Services.Client.HttpStack.ClientHttp;
 context.UseDefaultCredentials = false;
 context.Credentials = new NetworkCredential("administrator", "password", "domain");
 }
 . . . .

Put the following clientaccesspolicy.xml in the following location

“..\Program Files\Microsoft Dynamics CRM\CRMWeb”

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
 <cross-domain-access>
 <policy>
 <allow-from http-request-headers="*">
 <domain uri="*"/>
 </allow-from>
 <grant-to>
 <resource path="/" include-subpaths="true"/>
 </grant-to>
 </policy>
 </cross-domain-access>
</access-policy>

Once we are done with development we can set up the context in the following manner

 public partial class MainPage : UserControl
 {

private GGContext context;
 private String orgDataServerUrl;

public MainPage()
 {
 InitializeComponent();

// get the Server Url
 orgDataServerUrl = this.GetServerUrlFromContext();

// setup Context
 context = new GGContext(
 new Uri(String.Format("{0}/xrmservices/2011/organizationdata.svc/",
 orgDataServerUrl), UriKind.Absolute));

//This is important because if the entity has new
 //attributes added the code will fail.
 context.IgnoreMissingProperties = true;

}

private string GetServerUrlFromContext()
 {
 try
 {
 // If the Silverlight is in a form, this will get the server url.
 ScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
 ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
 ScriptObject pageContext = (ScriptObject)page.GetProperty("context");

String serverUrl = (String)pageContext.Invoke("getServerUrl");

// The trailing forward slash character from CRM Online needs to be
 // removed.
 if (serverUrl.EndsWith("/"))
 {
 serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
 }

return serverUrl;
 }
 catch
 {
 return String.Empty;
 }
 }
 }

Hope this helps.