Jan 152014
 

If you upgraded your system from CRM 2011 and used one of the tools out there that stores the contact image in the notes, and you want to set the entity image, here is an XrmToolbox plugin to help you. So, everyone that used (or continues to use) the crmattachmentimage or other solutions, you can now use this tool to help you migrate or use the new image field.

The XrmToolBox, created by Tanguy, can be downloaded from codeplex. It is a great set of tools for working with any Microsoft Dynamics CRM system. To upgrade my images that I have attached as notes to entityimage (the new CRM 2013 image field) I created a plugin for the XrmToolBox.

The ImageMigrator XrmToolBox plugin lists the entities that have image fields and will pull any png jpg or gif and attach it to the entity.

ImageMigrator Screenshot

Once it loads, click the refresh button to get a list of entities you can run the tool on, then select and click convert.

You can download just the plugin (dll) here.

You can download my source code for the project here.

Mar 082013
 

The XrmSvcToolkit on codeplex is a very small and easy to use toolkit for interacting with the Xrm web-services. TypeScript is a language for application-scale JavaScript development by compiling to plain JavaScript.

Once you’ve downloaded and installed TypeScript, you can use the Xrm 2011 TypeScript Definition from codeplex for the Xrm.Page. You can reference it using:

        /// <reference path=”Xrm2011.d.ts” />

You can reference the below Type Definition for the XrmSvcToolkit the same way:

        /// <reference path=”XrmSvcToolkit.d.ts” />

XrmSvcToolkit.d.ts

/* *****************************************************************************
TypeScript definition file for the XrmSvcToolkit
Author: Carlton Colter - http://www.mscrmblogger.com/
XrmSvcToolkit - http://xrmsvctoolkit.codeplex.com/
***************************************************************************** */

declare module XrmSvcToolkit {
    export function context(): {
        getAuthenticationHeader(): string;
        getCurrentTheme(): string;
        getOrgLcid(): number;
        getOrgUniqueName(): string;
        getQueryStringParameters(): string;
        getServerUrl(): string;
        getUserId(): string;
        getUserLcid(): number;
        getUserRoles(): string[];
        isOutlookClient(): bool;
        isOutlookOnline(): bool;
        prependOrgName(sPath: string): string;
    };
    export function serverUrl(): string;
    export function retrieve(opts: {
        entityName: string;
        id: string;
        select: string;
        expand: string;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function retrieveMultiple(opts: {
        entityName: string;
        odataQuery: string;
        async: bool;
        successCallback: Function;
        completionCallback: Function;
        errorCallback: Function;
    }): Object[];
    export function createRecord(opts: {
        entityName: string;
        entity: Object;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function updateRecord(opts: {
        entityName: string;
        id: string;
        entity: Object;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function deleteRecord(opts: {
        entityName: string;
        id: string;
        entity: Object;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function associate(opts: {
        entity1Id: string;
        entity1Name: string;
        entity2Id: string;
        entity2Name: string;
        relationshipName: string;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function disassociate(opts: {
        entity1Id: string;
        entity1Name: string;
        entity2Id: string;
        relationshipName: string;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function setState(opts: {
        entityName: string;
        id: string;
        stateCode: number;
        statusCode: number;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function execute(opts: {
        executeXml: string;
        async: bool;
        successCallback: Function;
        errorCallback: Function;
    }): Object;
    export function fetch(opts: {
        fetchXml: string;
        async: bool;
        successCallback: (result)=>void;
        errorCallback: Function;
    }): Object[];
}
May 102012
 

Do you need the value from a related entity, like a lookup? I had written this for CRM 4 a while back, and people use it, but I occasionally get questions about looking up other values in CRM. This bit of code will help you find those values on a related object. Below are two options to do this. Option 1: using the REST SDK and JSON2, and then Option 2: using Jaimie Ji’s XRM Service Toolkit.

Jaimie Ji’s XRM Service Toolkit provides a comprehensive set of JScript libraries for interacting with the SOAP and REST SDK through JavaScript. While Option 1 in this particular use case is fairly simple, when you start needing to do more advanced things, you may want to look at using that kit. It is fairly comprehensive and he keeps it up to date.

Option 1: Using the REST SDK and JSON2

Using the REST SDK is great, and there are some really good examples in the CRM SDK help file. Now in order to use the below code-block, you need to use JSON.

JSON, or JavaScript Object Notation, is a text format that is used to interchange data. JSON2.js is a lightweight javascript that convert the strings to javascript objects and vice-versa. The CRM REST SDK can return data in JSON format.

To get the code for JSON2, you can go here. You will need to embed this code into your javascript file or include json2.js along with the code below. Without it, you will not be able to parse the data properly, and the code below uses the JSON library in json2.js.

Ok, below we have 3 functions:

  • getServerUrl : which gets the server URL – taken from the CrmRestKit
  • Lookup_Changed : what you call when a lookup is changed
  • retrieveReqCallBack : the callback function that performs any actions

You would put Lookup_Changed in the change event of a lookup field and specify the attributes like one of the following:

  • ‘contactid’,’Contact’,’contactlookup’
  • ‘contactid’,’Contact’,’contactlookup’,[‘Telephone1′]
  • ‘contactid’,’Contact’,’contactlookup’,[‘Telephone1′,’FullName]

Then you’d put your actions inside the retrieveReqCallBack.

function getServerUrl() {  
    // From CrmRestKit.js
    var localServerUrl = window.location.protocol + "/" + window.location.host;
    var context = parent.Xrm.Page.context;

    if (context.isOutlookClient() && !context.isOutlookOnline()) {
        return localServerUrl;
    }
    else {
        var crmServerUrl = context.getServerUrl();
        crmServerUrl = crmServerUrl.replace(/^(http|https):\/\/([_a-zA-Z0-9\-\.]+)(:([0-9]{1,5}))?/, localServerUrl);
        crmServerUrl = crmServerUrl.replace(/\/$/, "");
    }
    return crmServerUrl;
}

function Lookup_Changed(attributeName, entityName, callbackId, columns) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    
    var lookup = Xrm.Page.data.entity.attributes.get(attributeName).getValue();
    if (lookup===null) {
        return false;
    }
  
    var id = lookup[0].id;
    if (id == null) { 
        return false;
    }
    
    var retrieveReq = new XMLHttpRequest();
    
    var url = ODataPath + "/"+entityName+"Set(guid'" + id + "')";
    if (columns !== undefined && columns !== null) {
        url = url + "?$select=" + columns.join(',');
    }
    
    retrieveReq.open("GET", url, true);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            if (this.status == 200) {
                var data;
                var jData;
                jData = JSON.parse(this.responseText);
                if (jData && jData.d && jData.d.results && jData.d.results.length > 0) {
                    data = jData.d.results[0];
                } else if (jData && jData.d) {
                    data = jData.d;
                }
                
                if (data == null) {
                    return;
                }
                retrieveReqCallBack(callbackId, data);
            }
        }
    };
    retrieveReq.send();
    return true;
}

function retrieveReqCallBack(calltype, data) {
    var toLookup=function(data) {
        if (data==null || data=="" || (data.Id==null)) {
            return null;
        }
    
        var result=new Array();
        result[0] = {};
        result[0].id = data.Id;
        result[0].name = data.Name;
        result[0].entityType = data.LogicalName;
        return result;
    }

    switch (calltype) {
        case 'pricelookup':
            Xrm.Page.data.entity.attributes.get("new_pricecategorylookup").setValue(toLookup(data.new_pricecategorylookup);
            break;
        case 'contactlookup':
            Xrm.Page.data.entity.attributes.get("insp_poctelephonenumber").setValue(data.Telephone1);
            break;
        default:
            break;
    }
}

Option 2: Using the XrmServiceToolkit with similar functions

Ok, now let’s assume you are using the XRM Service Toolkit, and you want to do the same thing, using a Lookup_Changed function and the retrieveReqCallBack function. Instead of embedding JSON and a method to get the server url, you can use the following:

function Lookup_Changed(attributeName, entityName, callbackId, columns) {
    var lookup = Xrm.Page.data.entity.attributes.get(attributeName).getValue();
    if (lookup===null) {
        return false;
    }
  
    if (lookup[0].id == null) { 
        return false;
    }
	
	XrmServiceToolkit.Rest.Retrieve(
        lookup[0].id,
        entityName,
        columns,
		null,
        function (result) {
            retrieveReqCallBack(callbackId, result);
        },
        function (error) {
            throw error;
        },
		true
    );
}

function retrieveReqCallBack(calltype, data) {
    var toLookup=function(data) {
        if (data==null || data=="" || (data.Id==null)) {
            return null;
        }
    
        var result=new Array();
        result[0] = {};
        result[0].id = data.Id;
        result[0].name = data.Name;
        result[0].entityType = data.LogicalName;
        return result;
    }

    switch (calltype) {
        case 'pricelookup':
            Xrm.Page.data.entity.attributes.get("new_pricecategorylookup").setValue(toLookup(data.new_pricecategorylookup);
            break;
        case 'contactlookup':
            Xrm.Page.data.entity.attributes.get("insp_poctelephonenumber").setValue(data.Telephone1);
            break;
        default:
            break;
    }
}

The XRM Service Toolkit does a lot, and I would suggest checking it out.

Sep 152011
 

In a previous post I wrote about a control I posted to codeplex that I used in my demos, a CRM Attachment Image Control.

It stored the images in the notes (still does – and currently does not have an option for storing elsewhere…). I still have not figured out how to put buttons on the ribbon that can fire the upload control, etc. Although, I recently found out that Marco Amoedo (blog: marcoamoedo.com, twitter: marcoamoedo) had leveraged the ImageTools for Silverlight to add WebCam support and I was already starting to play with it to add Gif support. I was able to work with him to get his modifications and add gif support. Now you have even more useful features that you can enable with a simple configuration change and a new silverlight web-resource.

Now, if you look in the bottom right, there is a webcam button next to the upload button that allows you to take a picture instead of uploading one. When you try and take the picture you will receive the following request for access.

So you may be asking: what is ImageTools for Silverlight? where did it come from?, and why are you using it? The answers are simple. According to the codeplex page for the ImageTools for Silverlight, it is "a library, which provides additional functionality for loading, saving and [manipulating] images from different sources and with different formats.&quot The reason to use it is simple, it is open-source, and it’s license allows me to use it (it is realeased under Ms-PL – the same license as my control on codeplex).

If you already use the CRM Attachment Image, you can just overwrite your xap file with the one from codeplex, but you will still need to edit the properties of the web-resource on your form to include |webcam=true. The new example syntax is:

field=new_imageattachmentid|subject='Contact''s Image'|prefix='img-'|webcam=true

So a special thanks to Marco for his help, this is a great change that I think a lot of people will be able to use.

If you need assistance in setting up the image control, I have it documented on codeplex, but here is a simple set of directions that work at the time of this article bieng posted:

  1. Create a solution
  2. Upload the xap as a web-resource
  3. Add your entity to the solution, and create a new text field on the entity that is 50 characters long, not searchable, preferably called something like attachmentid or savedattachmentid – it will be used to store the annotationid or the note that stores the attached image.
  4. Add the field to the form and make it not visible.
  5. Add the Web-Resource to the form
    • Check the checkbox to pass the id and type, etc.
    • In the parameters add the fields and their values seperated by a pipe |
  6. Save and publish the form.
  7. Test it!

The example config for the web-resource is before the instructions, and are very useful because you can just copy them and change the field new_imageattachmentid to your field name and it should work. There are a number of fields available to you if you want to change how the control functions, they are documented on codeplex, and they are:

  • field – The name of the field you are using to store the annotationid of the attachment. It is required, and the field MUST BE ON THE FORM (it does not need to be visible).
  • subject – The subject for attachments – the following substitutions are available (%s will be replaced with the name of the file )
  • prefix – The prefix for all attachment images (this is used to filter the results, etc)
  • hidebuttons – Used to hide the buttons that are in the silverlight control so that you can use the ribbon to control the application
  • savefirst – Used to set the message that is displayed on a form that is in Create Mode
  • webcam – Set to true if you want to enable the webcam it is not currently tide to hidebuttons

I added the following parameters at Bill’s request (Thanks Bill):

  • max-width: maximum width for all images
  • max-height: maximum height for all images
  • max-webcam-width: maximum webcam image width, overrides max-width for web-cam images
  • max-webcam-height: maximum webcam image height, overrides max-height for web-cam images
May 102011
 

The CRMAttachmentImage control downloads on codeplex have been updated to include gif and webcam support that I talk about in a new article that includes some instructions that may be helpful.

A while back Christian asked about this image control I had in a screenshot on one of my posts. And while it was ok, it was far from being something I would throw into a production environment. It was a starting point. I am proud to say that I have put the Silverlight control on codeplex at CRMAttachmentImage.CodePlex.com. It is in beta because I am still working on putting the buttons on the ribbon instead of in the control.

Contact Form - with Attachment Image Silverlight Control

** If anyone has any ideas for loading a file in JavaScript and sending it to the Silverlight control to load the data, I’m open to suggestions.

The image itself is stored as an attachment in the notes. This way the control is utilizing CRM and not an external system to handle the images. Simply put in order to use this your users will need to be able to read notes and create them. They will also need the "Customization > ISV Extensions" permission. If you are not seeing the images, and everything else is right, then try checking the permissions.

Instructions are posted on the codeplex site, but it is fairly straight forward to add to a form. First, you just upload the web-resource and create a text field to store the guid for the not (annotationid). It MUST BE ON THE FORM, but it does not need to be visible, and you probably don’t want to make it searchable. The web resource does require the id and type to be passed, and some additional parameters.

The parameters are separated by a pipe | instead of a comma. An example parameter is:

field=new_imageattachmentid|subject='Contact''s Image'|prefix='img-'

Check out the full parameter list at CRMAttachmentImage.CodePlex.com. If you have any suggestions or comments, please let me know.