Saturday, November 21, 2009

CRM 4.0 Read Only Iframe - A better solution




I already posted about creating a read only iframe in the past but the solution offered here is by far better and integrates nicely with CRM.
The idea, in a nut shell, is to create an upper blocking layer inside the iframe. The layer is decorated with an alpha filter which makes it look disabled and also presents a watermark text to the user. The helper object also accepts an alert text that is shown to the user when he tries to click inside the frame.
Feel free to change the opacity, colors and fonts for best appearance. This code, as usual, should be pasted into the onload event handler and published.



function IframeReadOnlyHelper(sIframeId)
{
var iro = this;
iro.Iframe = document.getElementById(sIframeId);
if (!iro.Iframe)
{
alert("IFRAME with id " + sIframeId + " is missing");
}

iro.WatermarkText = "";
iro.AlertMessage = "";

iro.OnIframeReady = function()
{
if (iro.Iframe.readyState != 'complete')
{
return;
}

var iframeDoc = iro.Iframe.contentWindow.document;
var iframeBody = iframeDoc.body;
var roSpan = iframeDoc.createElement("SPAN");

var roStyle = "overflow:hidden;";
roStyle += "position:absolute;";
roStyle += "z-index:1;";
roStyle += "left:0px;";
roStyle += "top:0px;";
roStyle += "height:100%;";
roStyle += "text-align:center;";
roStyle += "background-color:gray;";
roStyle += "font:72px Tahoma;";
roStyle += "filter:alpha(opacity=20)";

roSpan.style.cssText = roStyle;

iframeBody.appendChild(roSpan);

if (iro.WatermarkText != "")
{
roSpan.innerHTML = "<div style='height:100;'><br>" + iro.WatermarkText + "</div>";
}

if (iro.AlertMessage != "")
{
roSpan.attachEvent("onclick", function(){alert(iro.AlertMessage);});
}
}

iro.Disable = function()
{
iro.Iframe.onreadystatechange = iro.OnIframeReady;
iro.OnIframeReady();
}
}

function OnCrmPageLoad()
{
//Load IFRAME with any URL
var iframeActivity = document.all.IFRAME_account_association;
iframeActivity.src = "areas.aspx?oId=%7b50387202-6F73-DE11-9F19-0003FF230264%7d&oType=1&security=852023&tabSet=areaActivities";

//Use IframeReadOnlyHelper
var roIframe = new IframeReadOnlyHelper("IFRAME ID");
roIframe.WatermarkText = "Read Only";
roIframe.AlertMessage = "This Grid is Disabled";
roIframe.Disable();
}

OnCrmPageLoad();

Sunday, October 11, 2009

CRM 4.0 Make your announcements come to life




CRM has a nice feature (or at least a decent idea) called announcements which allows you to integrate and share textual messages with all CRM users.
The main issue with announcements is that the body or description field does not interprets hyper text.

Now wouldn’t it be nice to be able to integrate reach html messages into CRM using announcements. Although you can easily create your own reach text announcement mechanism and integrate it into CRM site map I actually find it more appealing leveraging an existing feature.

In order to force the announcement page support HTML is made a simple modification to the home / homepage / home_news.aspx. now, since modifying CRM files is unsupported consider the ramification before actually doing so.

The home_news.aspx page contains html that looks like this:

<body>

<table width="100%" height="100%">
<tr>
<td>
<table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div style="width:100%;height:100%;overflow-y:scroll;padding:10px; border: 1px solid #cccccc; background-color:#ffffff;">
<table width="100%" height="100%" cellspacing="2" cellpadding="3" border="0" style="table-layout:fixed;">
<col width="20"><col>
<% =RenderAnnouncements(false) %>
<tr height="100%" colspan="2"><td> </td></tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>


If you take a closer look at the generated html (using iedevtoolbar) you’ll notice that the announcement messages are rendered as table rows. I wanted to make as little change to this page as possible and still support HTML. In order to do so I used a simple technique which wraps the inner body content (table element) in a textarea and reads the textarea value into a new span element as innerHTML.

Here is how the page looks like after the modification is made:

<body>

<textarea style="display:none" id="anntext">
<table width="100%" height="100%">
<tr>
<td>
<table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div style="width:100%;height:100%;overflow-y:scroll;padding:10px; border: 1px solid #cccccc; background-color:#ffffff;">
<table width="100%" height="100%" cellspacing="2" cellpadding="3" border="0" style="table-layout:fixed;">
<col width="20"><col>
<% =RenderAnnouncements(false) %>
<tr height="100%" colspan="2"><td> </td></tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</textarea>

<span id="annhtml"></span>
<script> 
window.document.all.annhtml.innerHTML = document.all.anntext.value;
</script>

</body>


One thing that you need to minded of is that the html you paste in the announcement body should be a one liner. This is because the line breaks are interpreted as br elements.

That’s all, enjoy your new announcement feature.

CRM 4.0 cloning using entity mapping




In the past I wrote a few posts about cloning an entity using client side scripting. Most of the posts implemented complex script especially to non developers. I wanted to show you a simple cloning technique that leverages CRM built in features and can also work for CRM online.

The benefits of using this technique are:
1. Gain full control over which attributes are cloned
2. Ability to change which attributes are cloned without adding / changing your code.
3. Usage of a very simple script that does not need to be changed when reused.
4. Ability to easily track the parent record from which the cloned entity originated.

Following is the list of built in CRM features I am going to utilize in the post:
1. Creation of CRM form toolbar button
2. Creation of entity relationship.
3. Creation of mapping between related entities.
4. Adding simple script to the cloned entity onload handler.

So how can we actually make the above features work to our advantage. The main feature that lies in the heart of this technique is the ability to create a self referencing relationship between the an entity to itself and use the mapping wizard to tell CRM which attributes we what to pass from the parent record. Once we have that all that remains is to understand how CRM uses the mapping on the client side much like when you create a child contact record from within an account from.

If you take a close look at the URL that is used by CRM when you create a child related record you’ll notice that the URL uses a specific format that tells CRM what is the parent record id and type. Once you learn how to replicate this behavior you’re half way implementing this solution.
The following script which you’ll eventually need to paste in the entity onload event handler shows how to construct the child record or in our case the cloned record url:


Clone = function()
{
var cloneUrl = location.pathname + "?";
cloneUrl += "_CreateFromType=" + crmForm.ObjectTypeCode +
cloneUrl += "&_CreateFromId=" + crmForm.ObjectId +
cloneUrl += "&etc=" + crmForm.ObjectTypeCode + "#";

var cloneFeatures = 'toolbars=0,status=1,width=' + document.body.offsetWidth + "height=" + document.body.offsetHeight;

window.open(cloneUrl,'',cloneFeatures);
}


Once we have the script in place we need to add a toolbar button that will fire the actual cloning process.
Following is a sample clone button xml which you should add to your isv.config


<Entity name="gi_test">
<ToolBar ValidForCreate="0" ValidForUpdate="1">
<Button Icon="/_imgs/ico_18_debug.gif" JavaScript="Clone();">
<Titles>
<Title LCID="1033" Text="Clone" />
</Titles>
<ToolTips>
<ToolTip LCID="1033" Text="Clone" />
</ToolTips>
</Button>
<ToolBarSpacer />
</ToolBar>
</Entity>


Next you’ll need to create a self referencing relationship. To do that open the entity customization and select 1:N relationship. Then select create new relationship. Inside the relationship form choose the same entity on both sides of the relationship. You should select not to display the left navigation link. The bellow image encapsulates the process of creating the self referencing relationship.



Once the relationship is saved you’ll see a mapping link on the relationship form. Select the mapping link to open the mapping wizard.
Add as much mapping as required. Before you publish the entity consider the final step.



Finally, if you wish to track the originating record you only need to add the entity lookup (parent test in this case) that was created as a result of the self referencing relationship. You can also set the lookup field as read only so users can’t change it manually.



That’s it! publish your entity and you’re done.

Saturday, October 10, 2009

CRM 4.0 Creating Inline Toolbar and Buttons


Here is a nice usability feature that I really like. Currently CRM 4.0 only supports adding functional buttons via form toolbar. This suffices most of the time and mainly on strait forward data input forms. But as CRM takes giant leaps toward becoming a xRM platform, as an application architect and designer, you bow to search for more flexible ways to convey the system to the end user.

The following post presents a simple and effective way of adding an inline toolbar buttons at the section level. This is especially useful when creating complex data entry forms like designers and wizards that require multi-step / section oriented logic. It is also much more simpler to add a button to the form then going through the entire isv.config process.

Adding an inline toolbar to the form is pretty simple and involves 2 steps.
The first step is to add a new text field to the form, where you want the toolbar to appear (e.g. gi_toolbar) and hide it’s label through the form field customizations (i.e. double click on the field and uncheck display label on form checkbox).

Here is how it looks after the above step is completed:



The final step is to add the following code to the entity onload event handler and add an OnCrmPageLoad function which creates a new instance of InlineToolbar and adds the necessary buttons.

The end result looks like this:





function InlineToolbar(containerId)
{
var toolbar = this;
var container = document.all[containerId];

if (!container)
{
return alert("Toolbar Field: " + containerId + " is missing");
}

container.style.display = "none";
container = container.parentElement;

toolbar.AddButton = function(id,text,width,callback,imgSrc)
{
var btn = document.createElement("button");
var btStyle = new StyleBuilder();
btStyle.Add( "font-family" , "Arial" );
btStyle.Add( "font-size" , "12px" );
btStyle.Add( "line-height" , "16px" );
btStyle.Add( "text-align" , "center" );
btStyle.Add( "cursor" , "hand" );
btStyle.Add( "border" , "1px solid #3366CC" );
btStyle.Add( "background-color" , "#CEE7FF" );
btStyle.Add( "background-image" , "url( '/_imgs/btn_rest.gif' )" );
btStyle.Add( "background-repeat" , "repeat-x" );
btStyle.Add( "padding-left" , "5px" );
btStyle.Add( "padding-right" , "5px" );
btStyle.Add( "overflow" , "visible" );
btStyle.Add( "width" , width );

btn.style.cssText = btStyle.ToString();
btn.attachEvent("onclick",callback);
btn.id = id;

if (imgSrc)
{
var img = document.createElement("img");
img.src = imgSrc;
img.style.verticalAlign = "middle";
btn.appendChild(img);
btn.appendChild(document.createTextNode(" "));
var spn = document.createElement("span");
spn.innerText = text;
btn.appendChild(spn);
}
else
{
btn.innerText = text;
}

container.appendChild(btn);
container.appendChild(document.createTextNode(" "));

return btn;
}

toolbar.RemoveButton = function(id)
{
var btn = toolbar.GetButton(id)
if (btn)
{
btn.parentNode.removeChild(btn);
}
}

toolbar.GetButton = function(id)
{
return document.getElementById(id);
}

function StyleBuilder()
{
var cssText = new StringBuilder();
this.Add = function( key , value ){cssText.Append( key ).Append( ":" ).Append( value ).Append( ";" );}
this.ToString = function(){return cssText.ToString();}
}

function StringBuilder()
{
var parts = [];
this.Append = function( text ){parts[ parts.length ] = text;return this;}
this.Reset = function(){parts = [];}
this.ToString = function(){return parts.join( "" );}
}
}

/* Start Script Execution */
function OnCrmPageLoad()
{
window.GeneralToolbar = new InlineToolbar("gi_toolbar");
GeneralToolbar.AddButton("btnReset","Reset","15%",Reset_Click);
GeneralToolbar.AddButton("btnLookup","Lookup","10%",Lookup_Click);
//GeneralToolbar.RemoveButton("btnLookup");
GeneralToolbar.AddButton("btnAddNote","Create Note","16px",AddNote_Click,"/_imgs/ico_16_5_d.gif");
}

function Reset_Click()
{
alert('Reseting Fields...');
}

function Lookup_Click()
{
alert('lookup records...');
}

function AddNote_Click()
{
alert('Add new note');
}

Tuesday, September 29, 2009

CRM 4.0 Deploying a custom assembly


The most common and suggested deployment scenario for custom CRM web extensions (i.e. custom web service or web application) is to deploy them under the ISV folder (e.g. ISV / MyApp) and put the application assembly inside the CRMWeb \ bin folder (or wwwroot / bin when deployed on the default website).

As of rollup2 MS also recommends putting the product assemblies of your custom extensions in their own bin folder (i.e. ISV / MyApp / bin). This option also requires you to add an assembly directive

<%assembly name=”MyApp” %>


to all your pages so the asp.net will be able to bind to your server side code behind.

Here is an example:
Test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="MyApp.Test" %>
<%@ Assembly Name="MyApp" %>


Deployment Tree:

CRMWeb \ wwwroot
|-- ISV
|-- MyApp
|-- bin
|-- MyApp.dll


Looks simple enough but many find that this does not work and produces the error

[HttpException: Could not load type 'MyApp.Test'].


The reason this does not work is that in order for asp.net to recognize and load your assembly the assembly directive must be the first directive in the page e.g.

<%@ Assembly Name="MyApp" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="MyApp.Test" %>


And lastly a few tips to ensure successful deployment for both IFD and On-Premise environments:
Ensure that the MyApp folder is a regular Virtual Directory (not an application) – in other word your app will run under CRMAppPool.
Remove any application level nodes from your application web.config e.g.


Sunday, September 13, 2009

CRM 4.0 Records Per Page Wizard




A few months back I answered a thread on ms forums regarding running a workflow on more then 250 records which is the grid paging limit. I trimmed our record per page wizard and made it available for free on GI company website -> free wizards (left navigation).

If you’re looking for a cool productivity enhancement that lets you control how many records are displays per entity this one is surly something any user can appreciate. Feel free to send us feedbacks (feedback@gicrm.com).

RPP Wizard features:

  • Runs from CRM main application toolbar.

  • Identifies the current entity being browsed and loads with user the settings (either CRM paginglimit or saved setting).

  • Refreshes the current entity view.

  • Supports all views including associated views.

  • Supports quick and advanced find.

Thursday, September 10, 2009

CRM 4.0 Running an On Demand Workflow from JavaScript




Running a workflow from JavaScript is a great alternative to developing server side (web services) components. This is since the workflow designer is able to accomplish many programmable tasks without actually writing complex dot.net code. Implementing a simple JS framework that activates workflows is a great enhancement to any CRM project and can simplify many of your tasks.

The code integrates the notification (yellow ribbon) as a textual progress bar so the user can observe the progress of his actions.
The code also exposes a few properties that control the interval (in milliseconds) that checks the WF status, whether to refresh the page automatically or not and so forth.

The OnCrmPageLoad function below demonstrates the usage of the OnDemandWorkflow class. Paste the entire code in your onload event
and set the OnDemandWorkflow instance with the correct workflow id and properties.

Don’t forget to check your workflow as On Demand if you need to run them from code. You should also consider the logic that implements the client side call since user interaction can cause your workflow to run more then once.

Enjoy…


function OnDemandWorkflow()
{
var odw = this;
var request = null;

odw.DefaultProgress = new ProgressInfo();
odw.WorkflowId = "";
odw.OperationId = "";
odw.EntityId = "";
odw.Name = "";
odw.WorkflowStatus = -1;
odw.OnFinishCallback = null;

function UpdateNotification(msg)
{
if (!odw.DefaultProgress.Visible)
{
return;
}

var notification = document.all.Notifications;
notification.style.display = "inline";
notification.style.width = "100%";
notification.style.height = "20px";
notification.innerHTML = odw.Name + ": " + msg + "";
}

odw.Activate = function(sWorkflowId)
{
UpdateNotification("Activated");

if (sWorkflowId)
{
odw.WorkflowId = sWorkflowId
}

if (!odw.WorkflowId)
{
return UpdateNotification("Missing Workflow ID");
}

if (!odw.EntityId && crmForm.FormType == 2)
{
odw.EntityId = crmForm.ObjectId;
}
else if (!odw.EntityId)
{
return UpdateNotification("Workflow is missing an Entity name");
}

var xmlActReq = new StringBuilder();
xmlActReq.Append(GenerateSoapHeader());
xmlActReq.Append("");
xmlActReq.Append("");
xmlActReq.Append("").Append(odw.EntityId).Append("");
xmlActReq.Append("").Append(odw.WorkflowId).Append("");
xmlActReq.Append("
");
xmlActReq.Append("
");
xmlActReq.Append(GenerateSoapFooter());

odw.Execute("Execute",xmlActReq.ToString(),odw.ActivateEnd);
}

odw.Execute = function(sMethodName,sXmlRequest, fCallback)
{
if (request)
{
request.abort();
}
request = new ActiveXObject("Microsoft.XMLHTTP");
request.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
request.onreadystatechange = fCallback;
request.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/" + sMethodName);
request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
request.setRequestHeader("Content-Length", sXmlRequest.length);
request.send(sXmlRequest);
}

odw.ActivateEnd = function()
{
if (request.readyState == 4)
{
if (!validateResponse())
{
return;
}

odw.OperationId = request.responseXML.selectSingleNode("//Response/Id").nodeTypedValue;
odw.CheckStatus();
}
}

odw.CheckStatus = function()
{
var xmlChkReq = new StringBuilder();
xmlChkReq.Append(GenerateSoapHeader());
xmlChkReq.Append("");
xmlChkReq.Append("asyncoperation");
xmlChkReq.Append("{").Append(odw.OperationId).Append("}");
xmlChkReq.Append("");
xmlChkReq.Append("");
xmlChkReq.Append("statuscode");
xmlChkReq.Append("
");
xmlChkReq.Append("
");
xmlChkReq.Append("
");
xmlChkReq.Append(GenerateSoapFooter());

odw.Execute("Retrieve",xmlChkReq.ToString(),odw.CheckStatusEnd);
}

odw.CheckStatusEnd = function()
{
if (request.readyState == 4)
{
if (!validateResponse())
{
return setTimeout(odw.CheckStatus, odw.DefaultProgress.CheckInterval);
}

odw.WorkflowStatus = request.responseXML.selectSingleNode("//q1:statuscode").nodeTypedValue;

switch(parseInt(odw.WorkflowStatus))
{
case 30:
if (odw.DefaultProgress.RefreshWhenDone)
{
if (odw.DefaultProgress.RequestRefresh)
{
window.onbeforeunload = function()
{
return "Operation has succeeded, Do you wish to refresh the page?";
}
}
else
{
crmForm.detachCloseAlert();
}

setTimeout(function(){
window.location.reload();
},1000);
}

UpdateNotification("Operation has succeeded");
if (odw.OnFinishCallback)
{
odw.OnFinishCallback(odw);
}

break;
default:

switch(parseInt(odw.WorkflowStatus))
{
case 32: //canceled
UpdateNotification("Operation was canceled");
break;
case 22: //canceling
UpdateNotification("Operation is being canceled");
break;
case 31: //failed
UpdateNotification("Operation has failed");
break;
case 20: //In progress
UpdateNotification("Operation is in progress");
break;
case 21: //Pausing
UpdateNotification("Operation is pausing");
break;
case 10: //Waiting
UpdateNotification("Operation is waiting");
break;
case 0: //Waiting for resources
UpdateNotification("Operation is waiting for resources");
break;
}

return setTimeout(odw.CheckStatus, odw.DefaultProgress.CheckInterval);
}
}
}

function validateResponse()
{

var error = request.responseXML.selectSingleNode("//error");
var faultstring = request.responseXML.selectSingleNode("//faultstring");

if (error == null && faultstring == null)
{
return true;
}
else
{
odw.DefaultProgress.Visible = true;
if (error)
{
UpdateNotification(error.text);
}
else
{
UpdateNotification(faultstring.text);
}

return false;
}
}

function GenerateSoapHeader()
{
var soapHeader = new StringBuilder();
soapHeader.Append("");
soapHeader.Append(" soapHeader.Append(" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'");
soapHeader.Append(" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>");
soapHeader.Append(GenerateAuthenticationHeader());
soapHeader.Append("");
return soapHeader.ToString();
}

function GenerateSoapFooter()
{
var soapFooter = new StringBuilder();
soapFooter.Append("
");
soapFooter.Append("
");
return soapFooter.ToString();
}

function ProgressInfo()
{
this.RequestRefresh = true;
this.RefreshWhenDone = false;
this.Visible = false;
this.CheckInterval = 2000;
}

function StringBuilder()
{
var parts = [];
this.Append = function( text ){parts[ parts.length ] = text;return this;}
this.Reset = function(){parts = [];}
this.ToString = function(){return parts.join( "" );}
}
}

function OnCrmPageLoad()
{
if (confirm("Run Workflow"))
{
var odWorkflow = new OnDemandWorkflow();
/* The workflow name - for presentation */
odWorkflow.Name = "Create Task";
var odwProgress = odWorkflow.DefaultProgress;
/* true is default - true = user has to approve the page reload. */
odwProgress.RequestRefresh = false;
/* false is default - true = try to refresh when the workflow is done successfully. */
odwProgress.RefreshWhenDone = true;
/* false is default - true = see notification progress */
odwProgress.Visible = true;
/* 2000 is default - ping the server each x milliseconds */
odwProgress.CheckInterval = 1000;
odWorkflow.WorkflowId = "76f5cecb-987c-4635-8d78-66d2caa2f9ae";
/* default Entity Id - the entity instance id (guid) */
odWorkflow.EntityId = crmForm.ObjectId;
odWorkflow.OnFinishCallback = CallmeWhenTheWFIsDone
odWorkflow.Activate();
}
}

function CallmeWhenTheWFIsDone(odw)
{
if (odw.WorkflowStatus == 30)
{
alert('more code here');
}
}

OnCrmPageLoad();

Tuesday, September 8, 2009

Formatting CRM DateTime Field


As you might have noticed CRM DateTime field DataValue returns the following value: “Tue Sep 29 13:00:00 PDT 2009”
Sometimes you need to change the value to another format e.g. dd/mm/yyyy or mm-dd-yyyy hh:MM.
This is quite easy to do with C# since the format string is pretty extensive however the JavaScript Date object is pretty slim and so the only option is to write your own framework / prototype extension.

The following script extends the JavaScript Date Object and adds a toFormattedString function which accepts common format strings such as
dd – days, mm – months, yyyy – full year, hh – hours , MM – minutes , ss – seconds , ms – milliseconds , APM – AM/PM
You can extend the prototype function further if you require additional formatting.

Here is the code and usage example:

Date.prototype.toFormattedString = function(format)
{
var d = this;
var f = "";
f = f + format.replace( /dd|mm|yyyy|MM|hh|ss|ms|APM|\s|\/|\-|,|\./ig ,
function match()
{
switch(arguments[0])
{
case "dd":
var dd = d.getDate();
return (dd < 10)? "0" + dd : dd;
case "mm":
var mm = d.getMonth() + 1;
return (mm < 10)? "0" + mm : mm;
case "yyyy": return d.getFullYear();
case "hh":
var hh = d.getHours();
return (hh < 10)? "0" + hh : hh;
case "MM":
var MM = d.getMinutes();
return (MM < 10)? "0" + MM : MM;
case "ss":
var ss = d.getSeconds();
return (ss < 10)? "0" + ss : ss;
case "ms": return d.getMilliseconds();
case "APM":
var apm = d.getHours();
return (apm < 12)? "AM" : "PM";
default: return arguments[0];
}
});

return f;
}

function OnCrmPageLoad()
{
var d = new Date(crmForm.all..DataValue);
alert(d.toFormattedString("mm-dd-yyyy hh:MM:ss ms"));
alert(d.toFormattedString("dd/mm/yyyy hh:MM APM"));
}

OnCrmPageLoad();

CRM 4.0 Creating a Readonly picklist

CRM Picklist control (HTML select tag) does not have a read-only attribute like other input html controls. The only way to make it read-only is to disable it which grays out the control completely. Once you disable the Picklist you can’t change its border or font color (i.e. make it look like a read-only field). The only way to achieve the functionality is to change the control behavior so each time the user tries to change the Picklist value the Picklist initial value is re-selected.

Here is the JS code that does the job:


function OnCrmPageLoad()
{
ReadOnlyPicklist(crmForm.all.);
}

function ReadOnlyPicklist(picklist)
{
picklist.savedIndex = picklist.selectedIndex;
picklist.onchange = function()

{
this.selectedIndex = this.savedIndex;
}
}

OnCrmPageLoad();

CRM 4.0 Changing Tab Order

A while back i posted a solution for changing vertical tabbing to horizontal tabbing. The code ran a bit slow with lookups and so the code below is a revision of the previous posting with the fix.


function OnCrmPageLoad()
{
ReArangeTabIndex();
}

function ReArangeTabIndex()
{
for( var i = 0 ; i < crmForm.all.length ; i++ )
{
var element = crmForm.all[ i ];
if (element.tabIndex)
{
if (element.className == "ms-crm-Hidden-NoBehavior" || element.tagName == "A")
{
continue;
}

element.tabIndex = 1000 + (i*10);
}
}
}

OnCrmPageLoad();

Saturday, July 18, 2009

CRM 4.0 Setting a Picklist Default Value


Currently Dynamics supports setting default values for two attribute types: PicklistAttributeMetaddata (Picklist) and BooleanAttributeMetadata (bit fields). If you intend to set the default using custom code you need to follow the below process:

1. Retrieve the attribute metadata (unless you’re creating a new one) using RetrieveAttributeRequest
2. Cast the returned AttributeMetadata to a PicklistAttributeMetadata.
3. Set the picklist metadata Default value to an integer of you choice.
4. Update the attribute metadata using UpdateAttribute Request.
5. Publish the changes using PublishXml Request.

The bellow code is a working example which sets the account Relationship Type (customertypecode) picklist to Customer (value = 3).


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace GI.Sendbox
{
class Program
{
static void Main(string[] args)
{
try
{
/* Create Authenticatio Token */
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "MicrosoftCRM";

/* Create a CrmService end point */
CrmService crmService = new CrmService();
crmService.UnsafeAuthenticatedConnectionSharing = true;
crmService.Url = "http://localhost:5555/mscrmservices/2007/crmservice.asmx";
crmService.UseDefaultCredentials = true;
crmService.CrmAuthenticationTokenValue = token;

/* Create a MetadataService end point */
MetadataService metaService = new MetadataService();
metaService.Url = "http://localhost:5555/mscrmservices/2007/metadataservice.asmx";
metaService.UseDefaultCredentials = true;
metaService.UnsafeAuthenticatedConnectionSharing = true;
metaService.CrmAuthenticationTokenValue = token;

/* Retrieve the attribute metadata */
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
attributeRequest.EntityLogicalName = "account";
attributeRequest.LogicalName = "customertypecode"; //Relationship Type picklist

RetrieveAttributeResponse attributeResponse =
(RetrieveAttributeResponse)metaService.Execute(attributeRequest);

/* Cast the attribute metadata to a picklist metadata */
PicklistAttributeMetadata picklist =
(PicklistAttributeMetadata)attributeResponse.AttributeMetadata;

/* set the default value to "customer" (3) */
picklist.DefaultValue = (object)3;

/* update the attribute metadata */
UpdateAttributeRequest updateRequest = new UpdateAttributeRequest();
updateRequest.Attribute = picklist;
updateRequest.EntityName = "account";
updateRequest.MergeLabels = false;

metaService.Execute(updateRequest);

/* Publish the changes */
PublishXmlRequest request = new PublishXmlRequest();

request.ParameterXml = @"<importexportxml>
<entities>
<entity>account</entity>
</entities>
<nodes/>
<securityroles/>
<settings/>
<workflows/>
</importexportxml>";


PublishXmlResponse response =
(PublishXmlResponse)crmService.Execute(request);
}
catch(System.Web.Services.Protocols.SoapException sex)
{
Console.WriteLine(sex.Detail.OuterXml);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Tuesday, July 14, 2009

CRM 4.0 Logging user login information


Following is a simple example on how-to log a user interaction with CRM. The sample uses a simple plug-in that references the System.Web assembly. Once you create a reference to this assembly you’re able to read the HttpContext and consequently read the information you wish to log.

The plug-in hooks into the execute message which in most cases is the first event to fire (grid event). The plug-in also writes a cookie back to the browser to mark the logging operation so it only happens once while the main crm application is opened.

In the example I also create a simple logInfo entity with fields I’m interested in logging.

Please not that while reading information from the httpcontext and other objects like Request might be considered supported, reading information that CRM uses like httpcontext.items[“organizationName”] or writing information to a cookie might break your support. So when you write values back to the browser make sure you’re using a well defined naming convention that will always stay unique. And instead of reading the orgname from the items collection get it from the request url.


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using System.Web;

namespace GI.SandBox
{
public class LoginHandler : IPlugin
{
#region IPlugin Members

public void Execute(IPluginExecutionContext context)
{
if (context.MessageName != "Execute")
{
return;
}

if (context.Stage != MessageProcessingStage.BeforeMainOperationOutsideTransaction)
{
return;
}

if (!(context.CallerOrigin is ApplicationOrigin))
{
return;
}

HttpContext webContext = HttpContext.Current;
HttpCookie logInfo = webContext.Request.Cookies.Get("loginfo");

if (logInfo == null)
{
DynamicEntity logInfoEntry = new DynamicEntity();
logInfoEntry.Name = "gi_loginfo";

logInfoEntry.Properties.Add
(
new StringProperty
(
"gi_userhostaddress",
webContext.Request.UserHostAddress
)
);

logInfoEntry.Properties.Add
(
new StringProperty
(
"gi_useridentity",
webContext.User.Identity.Name
)
);

logInfoEntry.Properties.Add
(
new StringProperty
(
"gi_starturl",
webContext.Request.Path
)
);

logInfoEntry.Properties.Add
(
new StringProperty
(
"gi_hostname",
webContext.Request.Url.Host
)
);

if (webContext.Items["organizationName"] != null)
{
logInfoEntry.Properties.Add
(
new StringProperty
(
"gi_userhostaddress",
webContext.Items["organizationName"].ToString()
)
);
}

logInfoEntry.Properties.Add
(
new CrmDateTimeProperty
(
"gi_datetime",
new CrmDateTime(webContext.Timestamp.ToString())
)
);

TargetUpdateDynamic targetRecord = new TargetUpdateDynamic();
targetRecord.Entity = logInfoEntry;

UpdateRequest updateRequest = new UpdateRequest();
updateRequest.Target = targetRecord;

context.CreateCrmService(true).Execute(updateRequest);

logInfo = new HttpCookie("loginfo");
logInfo.Value = DateTime.Now.ToString();
webContext.Response.Cookies.Add(logInfo);
}
}

#endregion
}
}

Sunday, July 12, 2009

CRM 4.0 Cascading wizard




The Cascading wizard is a complementary add-on to dynamic mapping facility. Currently dynamics only supports mapping when a user creates a new child entity within a parent context (form). Knowing that many partners invest quite a bit of energy developing solutions that require cascading and having to deal with these types of requirements ourselves we decided to create a fully featured mapping / cascading wizard that enable us to complete these tasks with just a few clicks.

The CAW wizard has the following features which can save you hours of tedious development.

1.Mapping fields from a parent entity when a child entity is created outside of the parent form. For example: A common requirement might be to inherit account information when you create a new contact from dynamics contacts grid (view). Currently the account fields are only mapped if you create the contact from the account form.

2.Mapping fields from multiple parents. For example: you might have an entity that has lookups to more the 1 entity. When you create the entity you might want to inherit fields from any parent.

3.Cascading parent modifications to all children. For example: you might want to update all contacts under a certain account when the account main phone field (contact business phone) changes.

4.The ability to decide whether to inherit parent attributes only when the child field is empty. For example: you might want to inherit account information when the contact is created but want to enable the user to change the contacts fields afterwards. The CAW wizard enables you to decide whether field changes are cascaded when the child attribute is empty.

5.Cascading drilldown. One of the nicest features of this wizard is that it enables you to drill down the changes from the root entity to the bottom leaf.
For example: if you define an account to contact cascading rules and then define a contact to invoice cascading rule on the same fields. And then change the field on the account form the change is carried out to the invoice entity.

6.The wizard integrates seamlessly with the current mapping facility. And you can choose to utilize both or just use the CAW wizard.

Common CAW features: The wizard supports –
1. Both on-premise and partner hosted environments.
2. IFD – Internet facing deployment
3. 32 and 64 bit servers
4. Multi-Tenancy
5. All Languages
6. All Rollups

We made a video to illustrate the above features.
In order to play back the video, right click on the flash movie then click rewind and play.



If you have question regarding the wizard functionality you can ask them here of send your enquiry to support@gicrm.com

Sunday, July 5, 2009

CRM 4.0 Record Filter Wizard




The idea behind the RFW wizard is to create a security filter in the context of each entity data and user role and expose / grant access to records only when a certain condition is met or under a certain restriction. For example: an organization might want a specific salesperson role to see leads that are connected to a specific product family or allow a low-privileged role to only see accounts that their credit limit is between a certain range.The RFW wizard will always make sure that the returned data is within the security filter parameters.

Another good example that we use is creating a severity or scoring attributes that enables the organization to categorize each entity and then create a security filter that allows users to see data depending on the scoring attribute value.

Actually there is no limit to the type of security filters that you can create. You can construct any filter (simple or complex) using any business logic and utilizing existing or specialized attributes to achieve a high data aware security state.

The security filters are setup using the wizard User Interface without the need to write custom code.

The following demonstration is a simple example of how you can take advantage of the RFW wizard.
The first scenario creates a security restriction on the top business unit (a template) which hides accounts that their credit limit is between 100,000 and 1 million $. This means that all the views, quick create and advance find will adhere to this restriction and only return accounts that meet the security filter.

The second scenario overrides the template and creates a security filter on the system administrator role. This time the filter is setup on the credit hold attribute returning only accounts that their credit is not held.

The last scenario defines a security filter for a specific marketing manager and allows him to only to view accounts that their category is set to standard.

RFW Technical Information:

1.Support for Internet Explorer 8, Internet Facing Deployment - IFD, and all available rollups (1 – 5).
2.Support for all searchable entities (entities that you can search using advanced find)
3.Support for Security Hierarchy i.e. creating business unit templates, overriding the templates for each CRM role and creating specific security filters for users.
4.Supports all views e.g. (public, private , associated , quick find , advanced find , print pages etc)



If you have any questions regarding the RFW wizard post them here or send you enquiry to support@gicrm.com

Wednesday, July 1, 2009

CRM 4.0 Auto Sharing wizard




CRM 4.0 permission mechanism and access level rules can be quite limiting. This is especially true when privacy of data is required, visibility of records depends on business decisions or visibility depends on the source (role or user) which triggered the action. On other occasions you need to control visibility of record across sibling business units and business units that are not under the same branch.

Most customers overcome the problem by granting organization access to roles which needs work with data. Of course this is very problematic and reduces the security to minimum and so they usually start looking for solution like field level security which enables the organization to hide certain entity fields from a specific business unit, role or user.

Dynamics does address this problem using a mechanism called sharing. The problem with the sharing mechanism is that it’s a manual process which shifts the responsibility of sharing to the user. This behavior is rarely acceptable especially because sharing rules needs to adhere to specific business decisions and sharing logic.

I’ve seen some very interesting solutions that use dynamics workflow engine to facilitate the sharing of records. However we needed a comprehensive solution and so we developed the Auto Sharing wizard which addresses most scenarios (all of ours anyway).

Following is a technical description of the Auto Sharing wizard and what it can do for you.

1.Creation of Global Sharing rules - Fired by anyone (We use them as sharing templates and override with specific rules).
a.When the record is created
b.When the record match a specific snapshot (state)

2.Creation of Specific Sharing rules - Fired only when the current user or user role matches the sharing rule source (see video)
a.When the record is created
b.When the record match a specific snapshot (state)

3.Creation of a Sharing hierarchy e.g. Rules setup as global fire first  Rule setup at the Role level may override or add more sharing rules  Rule setup at the User Level overrides the Role level rules and used as Sharing rule exceptions.

4.Creation of Sharing rules that are integrated as a workflow step

Following is a list of scenarios that can be resolved using the wizard

Sharing of record only when a specific Role or User triggers the action
Conditional sharing either by using a snapshot query or by integrating the sharing rule in an “IF” workflow routine.
Sharing Record with lower non privileged business units, roles and users
Sharing Records with sibling Business units and Business unit that are not under the same branch

ASW Presentation – in order to rewind click on the flash movie; then rewind and play.



If you have questions regarding the wizard feel free to ask them here or send them to support@gicrm.com

Sunday, June 28, 2009

CRM 4.0 Working with Strings


Many CRM development tasks involve manipulation and concatenation of strings, whether it’s concatenating a Field DavaValue from 2 or more fields, building messages that involve dynamic data, constructing FetchXml Requests and Soap messages or constructing strings that contain CSS or other meaningful html information, in one way or another you end up writing a script that looks like the following examples:


//Exampe 1
var someValue = “The account number: ” + crmForm.accountnumber.DataValue + “ is not valid\n”;
someValue+= “More helpful info on how to fill a valid account number here.”

alert(someValue);

or

//Example 2
var iLeft = 100;
var iTop = 100;
var cssText = “position:absolute;left:” + iLeft + “;top:” + iTop + “;”;
document.all[“”].style.cssText = cssText;

or

//Example 3
var iTop = 50;
var iLeft = 50;
var iWidth = 800;
var iHeight = 600;
var windowFeature = “toolbars=0;width=” + iWidth + “,height=” + iHeight + “,top=” + iTop + “,left=” + iLeft;
window.open( “” , “” , windowFeatures);

There are several disadvantages of using this simple concatenation technique:
1.The first which is the most obvious and discussed here is the lack of multi-lingual support for text messages. If for instance you need to translate the text that appears in the first example above, how can you accomplish the task and still keep the dynamic value concatenation in the correct context?

2. Another major disadvantage involves construction of large strings such as when you build soap message or a large FetchXml queries which can dramatically decrease IE responsiveness and cause performance issues.

3. Large string that are constructed in this manner sometimes make it impossible to read and debug

The following JavaScript objects facilitates these types of tasks and will help you avoid the problems mentioned above.

The first code snippet facilitates the concatenation of strings using a class called StringBuilder (similar to C# System.Text.StringBuilder mechanism)

/* JS String Builder */
StringBuilder = function()
{
var parts = [];
this.Append = function( text ){parts[ parts.length ] = text;return this;}
this.Reset = function(){parts = [];}
this.ToString = function(){return parts.join( "" );}
}

//Usage
function OnCrmPageLoad()
{
//Solving example 2
var iLeft = 100;
var iTop = 100;
var cssText = new StringBuilder();
cssText .Append(“position:absolute;left:”).Append(iLeft).Append( “;top:”).Append(iTop).Append( “;”);
document.all[“”].style.cssText = cssText.ToString();

//Solveing example 3
var iTop = 50;
var iLeft = 50;
var iWidth = 800;
var iHeight = 600;

var windowFeature = new StringBuilder();
windowFeature.Append(“toolbars=0,”);
windowFeature.Append(“width=”).Append(iWidth).Append( “,”);
windowFeature.Append(“height=”).Append(iHeight).Append( “,”);
windowFeature Append(“top=”).Append(iTop).Append(“,”);
windowFeature.Append(“left=”).Append(iLeft);

window.open( “” , “” , windowFeatures.ToString());
}

OnCrmPageLaod();

The second code snippet contains an extension function to the built-in JavaScript string object which helps you solve the problem mentioned in example 1 above and also makes it possible to write code similar to the String.Format c# method.

String.prototype.Format = function( args )
{
var result = this.replace( /\{(\d{1})\}/ig ,
function match()
{
return args[arguments[1]];
}
);

return result;
}

function OnCrmPageLoad()
{
//Solve Exampe 1
var someValue = new StringBuilder();
someValue.Append(“The account number: {0} is not valid\n”.Format([crmForm.accountnumber.DataValue]));
someValue.Append(“More helpful info on how to fill a valid account number here.”);

alert(someValue.ToString())

//Solve Example 2
var iTop = 50;
var iLeft = 50;
var iWidth = 800;
var iHeight = 600;

//Create string template with place holders
var windowFeature = “toolbars=0;top={0},left={1},width={2},height={3}”;
//Format the String
windowFeature = windowFeature.Format([iTop,iLeft,iWidht,iHeight]);
window.open( “” , “” , windowFeatures);
}

OnCrmPageLoad();

The last example extends the StringBuilder class and creates a StyleBulder that is used to concatenate CSS rules with ease

StyleBuilder = function()
{
var cssText = new StringBuilder();
this.Add = function( key , value ){cssText.Append( key ).Append( ":" ).Append( value ).Append( ";" );}
this.ToString = function(){return cssText.ToString();}
}

//Usage
function OnCrmPageLoad()
{
//Solve Example 2
var iLeft = 100;
var iTop = 100;
var cssText = new StyleBuilder();
cssText.Add(“position”,”absolute”);
cssText.Add(“left”, iLeft);
cssText.Add(“top”,iTop);

document.all[“”].style.cssText = cssText.ToString();
}

OnCrmPageLoad();

I hope you find this interesting and helpful.

Saturday, June 27, 2009

CRM 4.0 Adding a helper button to text fields




Sometimes you want to attach a click event to a text field. Since CRM does not provide a way to associate a button with a CRM field you need to implement the functionality using JavaScript. The following TextHelperButton object helps you achieve that goal for any given text field.

When creating an instance of the TextHelperButton set the following parameters:
Image width – This is used to adjust the image positioning.
MouseOver image URL – The image that is displayed when you go over the button.
MouseOut Image URL – The default image URL
Click – A function to call when the user clicks on the image.

Paste the code inside the entity onload event and enjoy...


TextHelperButton = function(fieldId)
{
var fldButton = this;

fldButton.Field = crmForm.all[fieldId];

if (!fldButton.Field)
{
return alert("Unknown Field: " + fieldId);
}

fldButton.Click = null;
fldButton.Image = new ButtonImage();
fldButton.Paint = function()
{
var field_d = document.all[fldButton.Field.id + "_d"];
if (field_d)
{
field_d.style.whiteSpace = "nowrap";
field_d.appendChild(fldButton.Image.ToObject())
}
}

fldButton.MouseOver = function()
{
event.srcElement.src = fldButton.Image.MouseOver;
}

fldButton.MouseOut = function()
{
event.srcElement.src = fldButton.Image.MouseOut;
}

function ButtonImage()
{
this.MouseOut = "";
this.MouseOver = "";
this.Width = 21

this.ToObject = function()
{
var img = document.createElement("IMG");
img.onmouseover = fldButton.MouseOver;
img.onmouseout = fldButton.MouseOut;
img.onclick = fldButton.Click;
img.src = this.MouseOut;

var cssText = "vertical-align:bottom;";
cssText+= "margin:1px;";
cssText+= "position:relative;";
cssText+= "right:" + (this.Width + 1) + "px";
img.style.cssText = cssText;
return img;
}
}
}

function OnCrmPageLoad()
{
/* pass the name of the crm field as parameter */
var actnButton = new TextHelperButton("name");
/* set the image button width */
actnButton.Image.Width = 21; //integer
/* supply image rollover URLS */
actnButton.Image.MouseOver = "/_imgs/lookupOn.gif";
actnButton.Image.MouseOut = "/_imgs/lookupOff.gif";
/* supply an function that is called when the image is clicked */
actnButton.Click = Accountnumber_Click;
/* add the image next to the field */
actnButton.Paint();
}

function Accountnumber_Click()
{
alert('Account Number Field Clicked');
}

OnCrmPageLoad();

CRM 4.0 Creating a JS Resource Manager

The purpose of this post is to present a simple and effective way of handling multi-lingual text resources on the client (CRM) Form.

In most projects an application is built to address a single language. Knowing that from the get go simplifies the way developers weave (hard code) the application messages into each entity form.

Let’s assume, for example, that you need to validate that the account number starts with the letters “ACT ”. Your code might look like the following example:


if (/^ACT\s{1}/.test(crmForm.accountnumber.DataValue) == false)
{
alert(”Account number must begin with ACT ”);
}


This is a very simple and strait forward way to present messages to the user. However since CRM is a multi-lingual application using this approach is far from being a best practice. The reason is that your client might decide (eventually) to add another language to the system and once he does that you must rewrite you application to support the new language. Assuming you have a small amount of messages you might consider changing your code as follows:


if (/^ACT\s{1}/.test(crmForm.accountnumber.DataValue) == false)
{
if (USER_LANGUAGE_CODE == 1033) //English United States
{
alert(”Account number must begin with ACT ”);
}
else if (USER_LANGUAGE_CODE == 1043) //Dutch
{
alert(”Rekeningnummer moet beginnen met ACT ”);
}
}


Now, as long as the application stays small this solution should hold. However, applications tend to grow over time and from a certain point the amount of messages will be too overwhelming to manage in this manner.

Another reason why this approach is a bad practice is that is obligates or ties the client to an ever lasting development phase. The best approach is to shift the responsibility of handling multi-lingual tasks to the client and the best way to do that is to create a resource manager that enables you to support multi-lingual messages from your first line of code.

So how do we shift responsibility of translating our application messages to the client?
The simplest approach is to create a new text attribute for each message that you need to display. The text attribute display name can hold the message it self. For example:

New Attribute: new_msginvalidaccountnumber
Display Name: The account number must begin with “ACT “
Searchable: No
Required:No

Now, put the new attribute on the CRM form under a new tab called Labels and hide it when the form loads. E.g.


function OnCrmPageLoad()
{
document.all.tab4Tab.style.display = “none” //assuming that the fifth tab is the Labels tab.
}

OnCrmPageLoad();


Now, let’s transform the above code so it would support any language


/* --< Resource Manager >-- */
ResourceManager = function()
{
var rm = this;
rm.GetString = function( resId )
{
var resource = document.getElementById( resId );
if ( !resource )
{
/* Show missing label */
return "[" + resId + "]";
}

return crmForm.GetLabel( resource );
}
}
/* Create an instance of Resource Manager */
RM = new ResourceManager();

if (/^ACT\s{1}/.test(crmForm.accountnumber.DataValue) == false)
{
alert(RM.GetString(“new_msginvalidaccountnumber”));
}


Integrate the resource manager to each entity onload event.

Good luck…

Friday, June 12, 2009

Summarizing an Appointment field on a Parent Entity


Imagine you have a custom field called number of participants on and appointment entity and you want to summarize this field for all the appointments under the same regarding parent.

This looks simple at first glance i.e. register a plug-in on the parent post Create and Update messages and you’re done. However, since this entity is part of dynamics scheduling engine and affects rescheduling you also need to register your plug-in on the Book and Reschedule messages.

Actually the Book and Reschedule messages somewhat replace the Create and Update messages. That means that when you create a new Appointment the Book message is fired and when you Update an existing appointment the reschedule message is fired.

So why do we need to also register the plug-in on the Create and Update messages?
The answer is that when you reschedule or book an appointment and the user is not available at that point in time the scheduling engine halts the execution and enables the user to cancel the operation. If the user decide to disregard (ignore) that warning and save anyway then the Create or Update are fired to complete the operation.

Since the summarizing of the field can be a long operation you should also register the plug-in for asynchronous execution.

Another thing that is worth mentioning is code synchronization. Since CRM does not lock record and two users can update the same appointment at the same time it is also advisable to lock the process that updates the parent field to avoid data corruption.

Last Important remark: the regarding lookup (parent entity) is required for this operation. Since the Book and Reschedule messages don’t allow you to register Post Images you need to send the regarding field in each operation. E.g.

//Put this code in the appointment onload event handler

if (crmForm.regardingobjectid.DataValue != null)
{
crmForm.regardingobjectid.ForceSumbit = true;
}


Plug-in Registered on the Reschedule, Book, Create and Update Asynchronous Parent Pipeline


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace GI.Crm.Sandbox
{

public class SummarizeAppointmentFieldHandler : IPlugin
{
private Object SyncObject = new Object();

public void Execute(IPluginExecutionContext context)
{
/* Validates that the user is available */
if (context.OutputParameters.Contains(ParameterName.ValidationResult))
{
ValidationResult validationResult =
context.OutputParameters[ParameterName.ValidationResult] as ValidationResult;
if (validationResult.ValidationSuccess == false)
{
return;
}
}

/* Validate Target Entity */
if (!context.InputParameters.Contains(ParameterName.Target))
{
return;
}

DynamicEntity Target = context.InputParameters[ParameterName.Target] as DynamicEntity;

/*
We need both regarding (parent) entity id and number of participants field
Client side must Force Submit on regarding field
*/
if ( !Target.Properties.Contains("regardingobjectid") ||
!Target.Properties.Contains("gi_noofpart"))
{
return;
}

Lookup regardingObjectId = Target.Properties["regardingobjectid"] as Lookup;
/* Validate that the Appointment is Regarding the Correct parent entity */
if (regardingObjectId.type != "gi_custom")
{
return;
}

CrmNumber noofPart = Target.Properties["gi_noofpart"] as CrmNumber;

/* Validate the number of Participants */
if (noofPart.Value == 0)
{
return;
}

/* Synchronize access to this code block */
lock(SyncObject)
{
#region Retrieve all Regarding entity Appointments
QueryExpression allPartQuery = new QueryExpression();
allPartQuery.ColumnSet = new ColumnSet();
allPartQuery.ColumnSet.AddColumn("gi_noofpart");
allPartQuery.Criteria.AddCondition(
"regardingobjectid" , ConditionOperator.Equal , regardingObjectId.Value
);
allPartQuery.Distinct = false;
allPartQuery.EntityName = EntityName.appointment.ToString();

RetrieveMultipleRequest retMultiRequest = new RetrieveMultipleRequest();
retMultiRequest.Query = allPartQuery;
retMultiRequest.ReturnDynamicEntities = true;

RetrieveMultipleResponse retMultiResponse =
(RetrieveMultipleResponse)context.CreateCrmService(true).Execute(retMultiRequest);

#endregion

#region Summaries all Appointments Number of Participants
Int32 Summery = 0;
foreach(DynamicEntity appointment in retMultiResponse.BusinessEntityCollection.BusinessEntities)
{
if (appointment.Properties.Contains("gi_noofpart"))
{
Summery += ((CrmNumber)appointment.Properties["gi_noofpart"]).Value;
}
}
#endregion

#region Update Parent entity Number of Participants
/* Key Property */
Key parentEntityKey = new Key(regardingObjectId.Value);
KeyProperty parentEntityKeyProp = new KeyProperty("gi_customid", parentEntityKey);
/* Number of participants Property */
CrmNumberProperty noofPartProp = new CrmNumberProperty("gi_noofpart",new CrmNumber(Summery));

DynamicEntity parentEntity = new DynamicEntity(regardingObjectId.type);
parentEntity.Properties.Add(parentEntityKeyProp);
parentEntity.Properties.Add(noofPartProp);

TargetUpdateDynamic targetEntity = new TargetUpdateDynamic();
targetEntity.Entity = parentEntity;
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.Target = targetEntity;
context.CreateCrmService(true).Execute(updateRequest);
#endregion
}
}
}
}

Thursday, June 11, 2009

CRM 4.0 Workflow Query Wizard


The WQW wizard is a specialized query builder that we integrated into dynamics workflow engine. The wizard facilitates the creation of aggregate queries without the need to write custom code for each requirement that we have. This helps us create various complex workflow rules that are not available by the out of box workflow designer. A good usage example is when you need to create Monitoring / Alerting workflows or need to take some action depending on existing or non-existing amount of records that answer a specific set of conditions.

The WQW also facilitates the creation of specific business counters on the parent entity. This is done by updating the parent entity with the WQW result using the workflow built in functionality (update record step). One of the biggest advantages of using the WQW and the business counters is that it can help you create not-in queries.

Consider, for example, a scenario where you need to find accounts without contacts or open incidents.
by creating a WQW workflow step and a new account attribute (counter attribute) called number of accounts / number of open incidents you can write the WQW result to each attribute counter. This enables the user to retrieve all accounts that have 0 contacts / or 0 open incidents in each respective account counter.

The video demonstration illustrates 2 simple scenarios that make the WQW such a wonderful workflow addition.
The first scenario monitors the amount of long duration outgoing calls that are made by a user. The second scenario alerts a manager when too many on-hold cases are open for a specific user. These are just examples. There is no limit on the type of Alerts or Actions that you can take using the wizard. As long as you are able to build a query around your requirement the wizard will facilitate the actions and enable you to easily create workflow rules depending on the their results.

Another feature that the WQW has to offer is the dynamic binding of values in the current workflow context. If you take a look at the second scenario you’ll notice that the WQW uses the owner attribute dynamically. Since the owner is not known at design time the values are taken from the context at runtime and integrated into the query.

I’m sure this addition will save you hours of tedious development effort. If you have question regarding the wizard fill free to post them here.
The wizard will be available on our website next week. Enjoy…

In order to rewind right click on the flash movie and select play

Wednesday, June 10, 2009

CRM 4.0 Queue Security Manager Wizard




As you know, Queues in CRM are organizational entities. This means that if the user role has read access rights on the Queue entity he can see all Queues. Organization that uses Queues as a concept usually search for a way to moderate Queue access based on Business Unit, Role and sometimes specific Users. This type of requirement is especially important for call centers and application that use queues as intermediary facilities or what I call bus stops for work that spin many users and business processes.

Our Product also makes substantial use of Queues throughout our solution. Knowing that the way CRM handles Queues will not serve the purpose we built a wizard that enables us to define Queue visibility for any security settings. If you’re looking for a wizard like solution that enables you to control Queue access with a few clicks (No Coding Required) then you’ll love this wizard.

The QUM wizard, as all our wizards, supports rollup4, IE8, IFD and can be installed on a 64 bit environment.



The wizard can be obtained as a stand alone product however we also included it in our security package and partner starter pack for no additional cost.

The wizard is now available on GI online website

Sunday, May 31, 2009

CRM 4.0 Embedding User Signature in CRM Web Client

One of the main features that the CRM email web client is missing is an automatic stationary signature. Although a user (or an administrator) can create a predefined signature and embed it before sending the email the web client requires the user to fill the TO (or CC) field in advance and then pick out the signature template using the Insert Template button. For most of us who gotten used to using advanced editors like outlook this seems like a major step backwards.

In order to enhance the user experience and demonstrate to strength and simplicity of dynamics while I’m at it I wrote a post that automates the process. The automated signature makes use of CRM’s email template feature. Once the Global email template (signature) is in place you need to extract its id (templateid) and use it in your code.

In order to retrieve the template id you can run this following query against the filteredtemplate view:

SELECT TEMPLATEID FROM FILTEREDTEMPLATE WHERE TITLE = ‘USER SIGNATURE’


The nice thing about dynamics is that most UI features also have an API manifestation. In this case it’s the ability to instantiate email templates by using the InstantiateTemplateRequest. The InstantiateTemplateRequest receives a templateid, objectid and objecttype. The objectid and type are used as context so the template is able to retrieve information that is specific to the recipient entity. Since we are only interested in the user information the objectid and type are filled with the email owner which is the current user.

Copy the following code to the email onload event and enjoy…


function Signature(companyTemplateId)
{
var sig = this;
var emailIframe;
var emailBody;

sig.TemplateId = companyTemplateId;

sig.Load = function()
{
try
{
var xml = '' +
'' +
'' +
GenerateAuthenticationHeader() +
' ' +
' ' +
' ' +
' ' + sig.TemplateId + '' +
' ' + crmForm.ownerid.DataValue[0].typename + '' +
' ' + crmForm.ownerid.DataValue[0].id + '' +
'
' +
'
' +
'
' +
'
' +
'';

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

var resultXml = xmlHttpRequest.responseXML;
if (xmlHttpRequest.status == 200)
{
emailBody = resultXml.selectSingleNode("//q1:description").text;
emailIframeReady();
}
}
catch(err)
{
alert(err.description);
}
}

function emailIframeReady()
{
if (emailIframe.readyState != 'complete')
{
return;
}

emailIframe.contentWindow.document.body.innerHTML = emailBody;
}

emailIframe = document.all.descriptionIFrame;
emailIframe.onreadystatechange = emailIframeReady;
}

function OnCrmPageLoad()
{
if (crmForm.FormType == 1)
{
var signature = new Signature("90886EF8-1A4D-DE11-9CF8-0003FF230264");
signature.Load();
}
}

OnCrmPageLoad();

Saturday, May 30, 2009

CRM 4.0 Finding Entity URL

This is a small trick you can use to find what URL is stored behind each CRM vanilla (customizable) entity. You can use as part of your code (see my post about cloning an entity using JavaScript) or just run it in IE address bar. Although it seems this function is not going anywhere there is a chance it won’t be there on the next version.

Address bar function:
javascript:void( alert( getObjUrl( 2 ) ) )


The getObjUrl function utilizes the GetWindowInformation function which receives the entity object type code e.g. 2 – contact and return an object containing the entity Url and window size (width and height). Here is an example of how to use it inside your code:

var contactUrlInfo = GetWindowInformation(2);
var windowFeatures = “height=” + contactUrlInfo.Height + “,width=” + contactUrlInfo.Width + “,toolbars=0”;
window.open( prependOrgName( contactUrlInfo.Url ) , “contact window” , windowFeatures );


So how does this work?
The GetWindowInformation function refers to “/_common/windowinformation/windowinformation.aspx” URL. If you open this page in the address bar and take a look at the page source you’ll see a script that look like this:


function CRMWindowInfo(sUrl, iXOffset, iYOffset)
{
this.Width = parseInt(iXOffset, 10);
this.Height = parseInt(iYOffset, 10);
this.Url = sUrl;
}
function GetWindowInformation(iObjectType) {
switch (parseInt(iObjectType, 10))
{
case Account: return new CRMWindowInfo("sfa/accts/edit.aspx",1000,560);
case List: return new CRMWindowInfo("ma/lists/edit.aspx",820,560);
//and so on…
}
}


In order not to rely on ms functionality you can either work with static values or create your own page under the isv folder the returns similar js.

Friday, May 29, 2009

CRM 4.0 Show Associated-View in IFRAME (AssocViewer)

This post is complementary to the other posts that discuss presenting a CRM gird inside an IFRAME. As usually when you display an associated view inside an IFRME some of MS functionality breaks e.g. the automatic refresh when you add an existing member. This post uses the same technique as the N2NViewer but overrides the ms _locAssocOneToMany function in order to know when to refresh the grid.

The object exposes the following properties:
1. ParentId – this is the parent entity key. If not specified the viewer uses the current entity crmForm.ObjectId.
2. ParentOtc – this is the parent object type code. Again if not specified the crmForm.ObjectTypeCode is used.
3. RelationshipName – this is the relationship id as it appears in customization.
4. Tabset – this is the name of the tabset parameter which is required for the associated view to work. Use the iedevtoolbar to extract this parameter.

Enjoy...


function OnCrmPageLoad()
{
var assocViewer = new AssocViewer("IFRAME_RelatedContacts");
/* Optional - crmForm.ObjectId */
assocViewer.ParentId = 'D74D44AD-36D0-DC11-AA32-0003FF33509E';
/* Optional - crmForm.ObjectTypeCode */
assocViewer.ParentOtc = 1;
/* Mandatory - relationship schema name */
assocViewer.RelationshipName = "contact_customer_accounts"
/* Mandatory - tabset query string parameter */
assocViewer.Tabset = "areaContacts";
assocViewer.Load();
}

function AssocViewer(iframeId)
{
var av = this;
if (crmForm.FormType == 1)
{
return;
}

av.IFrame = document.all[iframeId];
if (!av.IFrame)
{
alert("Iframe " + iframeId + " is missing!");
}

var _locAssocOneToMany = null;
av.ParentId = crmForm.ObjectId;
av.ParentOtc = crmForm.ObjectTypeCode;
av.Tabset = null;
av.RelationshipName = null;

av.Load = function()
{
if (av.ParentId == null || av.ParentOtc == null || av.Tabset == null || av.RelationshipName == null)
{
return alert("Missing Parameters: ParentId or ParentOtc or Tabset Name!");
}
var security = crmFormSubmit.crmFormSubmitSecurity.value;
av.IFrame.src = "areas.aspx?oId=" + av.ParentId + "&oType=" + av.ParentOtc + "&security=" + security + "&tabSet=" + av.Tabset
av.IFrame.onreadystatechange = av.OnIframeReady;
}

av.OnIframeReady = function()
{
if (av.IFrame.readyState != 'complete')
{
return;
}

av.IFrame.contentWindow.document.body.scroll = "no";
av.IFrame.contentWindow.document.body.childNodes[0].rows[0].cells[0].style.padding = "0px";

_locAssocOneToMany = locAssocOneToMany;
locAssocOneToMany = av.locAssocOneToMany;
}

av.locAssocOneToMany = function(iType, sRelationshipName)
{
_locAssocOneToMany(iType,sRelationshipName);
if (sRelationshipName == av.RelationshipName)
{
av.IFrame.contentWindow.document.all.crmGrid.Refresh();
}
}
}

//Entry Point
OnCrmPageLoad();

Tuesday, May 26, 2009

CRM 4.0 Multi Lingual Support in Plug-ins

The following code presents a simple yet very effective way to handle and return multi-lingual error messages form a plug-in.

So how does it work?

Basically I created a base class for Custom Exceptions. All custom exceptions that you use in your code derive from this class. The base class overrides the Exception class Message property and returns the error message from a resources dictionary.

The resource dictionary holds the translations for each local id e.g. (1033, 3082). When an exception is thrown the user local id (LCID) is taken from the current running thread Culture Info object.

The Inner translation dictionary manages the each error message depending on the exception type. This way when the code throws a specific exception the correct error message is fetched from the dictionary.

Enjoy…


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.Web.Services.Protocols;

namespace Empty.PlugIn
{
public class Handler : IPlugin
{
#region IPlugin Members
/// <summary>
/// Resource Dictionary
/// </summary>
public static Dictionary<Int32, Dictionary<Type, String>> Resources;
public void Execute(IPluginExecutionContext context)
{
if (Resources == null)
{
Resources = new Dictionary<Int32, Dictionary<Type, String>>();

Dictionary<Type, String> English = new Dictionary<Type, String>();
English.Add(typeof(Exception), "General Exception");
English.Add(typeof(SoapException), "CRM Exception");
English.Add(typeof(InvalidCustomException), "Invalid Custom Exception");
English.Add(typeof(UnKnownPluginException), "UnKnown Plugin Exception");
Resources.Add(1033, English);

Dictionary<Type, String> Spanish = new Dictionary<Type, String>();
Spanish.Add(typeof(Exception), "Excepciףn general");
Spanish.Add(typeof(SoapException), "Excepciףn de CRM");
Spanish.Add(typeof(InvalidCustomException), "Excepciףn personalizado no vבlido");
Spanish.Add(typeof(UnKnownPluginException), "Excepciףn Desconocida Plugin");
Resources.Add(3082, Spanish);
}

try
{
//throw new Exception();
//throw new SoapException();
throw new UnKnownPluginException();
}
catch(Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}

public abstract class CustomException : Exception
{
private Int32 DefaultLanguage = 1033;
/// <summary>
/// override default message prop
/// </summary>
public override string Message
{
get
{
return this.GetResource(this.GetType());
}
}
/// <summary>
/// Get the resource by exception type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected string GetResource(Type type)
{
Int32 uiLcid = System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;

if (Resources.ContainsKey(uiLcid))
{
return Resources[uiLcid][type];
}

return Resources[this.DefaultLanguage][type];
}
}

public class InvalidCustomException : CustomException
{
}

public class UnKnownPluginException : CustomException
{
}

#endregion
}
}

Sunday, May 3, 2009

CRM 4.0 Using attribute mapping in code


This is a quick and dirty way of getting CRM attribute mapping. So what exactly can you do with it? One option would be to use it in order to retrieve parent context information when you use CrmService to create new entities. For example, when you create a new contact you might want to get the account information that would normally map to contact when used from the CRM UI.

One of the challenges of using SDK is to mimic some of the functionalities that exist in the UI e.g. required field and attribute mapping when a child entity is created in the context of a parent entity. This type of mapping does not exist out of the box and requires you to write custom code.

The following example is a generic way to extract mapping information from CRM. So what are the pros and cons of using this technique?
The biggest advantage is that you’re able to you CRM customizations which make the configuration process worth while.
The disadvantages are that the default CRM mapping (attributemap entity) does not hold the type of the attributes e.g picklist or lookup and the information returned form the CRM also contains inner mappings of picklist and lookups e.g. parentcustomeridname and parentcustomriddsc.

So how can we overcome these disadvantages?
The attribute type can easily be retrieved using the metadata service RetrieveAttributeRequest. The problem is that this call to metadataservice is very slow so you also need to cache the data in order to use it efficiently.
The inner mapping can be ignored if you exclude picklist and lookup attributes that end with name of dsc.

The code does not cache the mapping information and does not show you how to create a new contact with parent mapping but presents a poc of how to retrieve the mapping information for further use.

The following is what the program prints to the console:

paymenttermscode --> paymenttermscode - Type: Picklist
telephone1 --> telephone1 - Type: String
accountid --> parentcustomerid - Type: Customer
name --> parentcustomeridname - Type: String
deletionstatecode --> parentcustomeriddsc - Type: Integer
address1_addresstypecode --> address1_addresstypecode - Type: Picklist
address1_city --> address1_city - Type: String
address1_country --> address1_country - Type: String
address1_county --> address1_county - Type: String
address1_line1 --> address1_line1 - Type: String

Here is the code, simply create a new console application and dump the class inside the program.cs file


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy.Metadata;
using Microsoft.Crm.Sdk.Metadata;

namespace EntityMapping
{
class Program
{
static void Main(string[] args)
{
List<AttributeMapping> AcctContMap = GetAttributeMapping("account", "contact");

foreach(AttributeMapping attributeMap in AcctContMap)
{
Console.WriteLine
(
String.Format
(
"{0} --> {1} - Type: {2}",
attributeMap.FromEntityName,
attributeMap.ToEntityName,
Enum.GetName(typeof(AttributeType),attributeMap.AttributeType)
)
);
}
}

public class AttributeMapping
{
public String FromEntityName;
public String ToEntityName;
public AttributeType AttributeType;

public AttributeMapping(String fromEntityName,
String toEntityName,
AttributeType typeofAttribute)
{
this.FromEntityName = fromEntityName;
this.ToEntityName = toEntityName;
this.AttributeType = typeofAttribute;
}
}

private static List<AttributeMapping> GetAttributeMapping(String fromEntity, String toEntity)
{
DynamicEntity entityMap = GetEntityMapping(fromEntity, toEntity);
List<BusinessEntity> startMap = RetieveAttributeMappingByEntityMap(entityMap);
List<AttributeMapping> endMap = new List<AttributeMapping>(startMap.Count);

foreach (DynamicEntity attributeMap in startMap)
{
String targetAttribute = attributeMap.Properties["targetattributename"].ToString();
String sourceAttribute = attributeMap.Properties["sourceattributename"].ToString();
endMap.Add(
new AttributeMapping(sourceAttribute,targetAttribute,
GetAttributeType(toEntity,targetAttribute))
);
}

return endMap;
}

private static List<BusinessEntity> RetieveAttributeMappingByEntityMap(DynamicEntity entityMap)
{
Guid entityMapId = ((Key)entityMap.Properties["entitymapid"]).Value;
QueryExpression attributeQuery = GetAttributeQuery(entityMapId, new AllColumns());
return RetrieveMultiple(attributeQuery);
}

private static AttributeType GetAttributeType(string entityLogicalName, string attributeLogicalName)
{
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
attributeRequest.EntityLogicalName = entityLogicalName;
attributeRequest.LogicalName = attributeLogicalName;
RetrieveAttributeResponse attributeResponse =
(RetrieveAttributeResponse)GetMetaService("http://moss:5555/","MicrosoftCRM").Execute(attributeRequest);
return attributeResponse.AttributeMetadata.AttributeType.Value;
}

private static MetadataService GetMetaService(string serverUrl, string orgName)
{
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = orgName;

MetadataService service = new MetadataService();
service.Url = String.Format("{0}mscrmservices/2007/metadataservice.asmx", serverUrl);
service.PreAuthenticate = false;
service.UnsafeAuthenticatedConnectionSharing = true;
service.CrmAuthenticationTokenValue = token;
service.UseDefaultCredentials = true;

return service;
}

private static List<BusinessEntity> RetrieveMultiple(QueryExpression query)
{
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
request.ReturnDynamicEntities = true;
RetrieveMultipleResponse response =
(RetrieveMultipleResponse)GetCrmService(
"http://moss:5555/","MicrosoftCRM").Execute(request);
return response.BusinessEntityCollection.BusinessEntities;
}

private static CrmService GetCrmService(string serverUrl, string orgName)
{
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = orgName;

CrmService service = new CrmService();
service.Url = String.Format("{0}mscrmservices/2007/crmservice.asmx",serverUrl);
service.PreAuthenticate = false;
service.UnsafeAuthenticatedConnectionSharing = true;
service.CrmAuthenticationTokenValue = token;
service.UseDefaultCredentials = true;

return service;
}

private static DynamicEntity GetEntityMapping(String fromEntity, String toEntity)
{
QueryExpression query = new QueryExpression(EntityName.entitymap.ToString());
query.ColumnSet.AddColumn("entitymapid");
query.Criteria.AddCondition(
new ConditionExpression("sourceentityname",ConditionOperator.Equal,
new object[]{fromEntity})
);
query.Criteria.AddCondition(
new ConditionExpression("targetentityname",ConditionOperator.Equal,
new object[]{toEntity})
);

List<BusinessEntity> entityMapping = RetrieveMultiple(query);
return entityMapping[0] as DynamicEntity;
}

private static QueryExpression GetAttributeQuery(Guid entityMapId, ColumnSetBase columnSet)
{
QueryExpression query = new QueryExpression(EntityName.attributemap.ToString());
query.ColumnSet = columnSet;
query.Criteria.AddCondition(
new ConditionExpression("entitymapid",ConditionOperator.Equal,entityMapId.ToString())
);
return query;
}
}
}