1/30/14

MSCRM Get User Information with JavaScript

When working with Dynamics CRM forms, we can use the XRM client object model to query the fields and controls on the page. A common field on every form is the current user id. This however only provides the internal system id or GUID. When we need more information about the user, we can use the ODATA web services to get additional information.

This script provides us with a helper function to enable us to find additional information about the current logged on user.

if (typeof (OGBIT) == "undefined") { OGBIT = {}; }
OGBIT.UserInfo = {   
    Get: function () {

        var userInfo = {};
        if (self.userName == '') {
        var serverUrl = window.location.protocol + "//" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
           
            var userId = Xrm.Page.context.getUserId();
            var req = serverUrl + "/xrmservices/2011/OrganizationData.svc/SystemUserSet(guid'{0}')?$select=EmployeeId,FullName,InternalEMailAddress,SystemUserId,DomainName".replace('{0}', userId);
            try {
                $.ajax({
                    type: "GET", contentType: "application/json; charset=utf-8", datatype:"json",async:false,
                    url: req,
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    success: function (data, textStatus, XmlHttpRequest) {
                        userInfo = data.d;
                        userInfo.status = true; //dynamic property
                    },
                    error: function (XmlHttpRequest, textStatus, errorObject) {
                        userInfo.status = false;
                        //add error handling

                    }
                });
            } catch (e) { }
        }
        return userInfo;
    }
}

The script first calls the getUserId method of the page context. This returns the system id which we can then use to make an ODATA request to get the additional user information. The ODATA query to get the user information has this format:

SystemUserSet(guid'{0}')?$select=EmployeeId,FullName,InternalEMailAddress,SystemUserId,DomainName

The SystemUserSet allows us to query the System User entity.  We query for the current user with the guid’{0}’ parameter. The $select query option is used to indicate what additional fields should be returned. Those fields are listed below:

Parameters:
Field Name
Description
EmployeeId
employee id
FullName
First and last name
InternalEMailAddress
Email
SystemUserId
Internal ID or GUID
DomainName
Username with this format:
DomainName\Username

The following snippet can be used to test the script. With this function, we just call the Get method and assign the returning information into local variables.

function GetUserInfo() {
    if (typeof (OGBIT.UserInfo) != 'undefined') {
        var info = OGBIT.UserInfo.Get();
        if (info.status) {
            var empId = info.EmployeeId;
            var name = info.FullName;
            var email = info.InternalEMailAddress;
            var userName = info.DomainName;
            var id = info.SystemUserId;
        } else {
            alert('Unable to find user');
        }
    }
}


I hope this Script helps you get more understanding on how to interact with MS CRM.

1/4/14

IFrame SharePoint Page

Most websites do not allow their content to be loaded in IFRAMEs.  The main reason is to prevent “web framing” in which a remote website frames another to get clicks.  This is also applicable to SharePoint applications in which the frame options are set to allow SAMEORIGIN only which means that framing is only allowed to pages on the same domain.

In SharePoint, there is a way to enable your application to allow the pages to be rendered in an IFRAME. This can be done by adding the following Web part to the master or single page.

<WebPartPages:AllowFraming runat="server"/>

This webpart enables the SharePoint content to be rendered in an IFrame by websites hosted in other domains.

Also note that this meta-tag does not work on SharePoint 2013:


                <meta name=”X-FRAME-OPTIONS” content=”ALLOW” />

12/21/13

ASP.Net Show Assembly Build Date

When creating an about page for a web application, we often add the build date information. To get the build date, we can query the executing assembly file and get the last write time property.

/// <summary>
/// returns the file write date
/// </summary>
/// <returns></returns>
private static string GetAssemblyDate()
{
string date = string.Empty;
try
{
var assembly = Assembly.GetExecutingAssembly();
var fileInfo = new FileInfo(assembly.Location);
var writeTime = fileInfo.LastWriteTime;
date = String.Format("{0} {1}", writeTime.ToShortDateString(), writeTime.ToShortTimeString());
}catch(Exception ex)
{
//log exception info
}
return date;
}

This helper method reads the file properties of the assembly and returns the date and time information. This is the same date-time information that we would find when using Windows Explorer.  The date time information return by this method has this format:

                MM/DD/YYYY hh:mm am/pm


I hope this helps some of you.

12/14/13

MSCRM Adding Notes With JavaScript

In Dynamics CRM, users can add notes to make comments about certain changes that were made to a record. In some instances, there may be a requirement to automate the creation of notes based on certain field information changes.  

The challenge with notes is that it is not a field on the entity. It is actually a 1:N association which is displayed on the form with an embedded IFRAME. This means that we can’t just populate a field, but instead, we need to call the REST web services on dynamics to request the creation of the note.
To handle this, we can create a simple JavaScript object that handles the web service call (NoteManager) and another object to the handle the test of the creation of the notes (TestNotes):

NoteManager Script:

if (typeof (OGBIT) == "undefined") { OGBIT = {}; }
OGBIT.NoteManager = {
    AddNote: function (params, entitySet, onComplete, onError) {
        var self = OGBIT.NoteManager;
        var serverUrl = self.GetServerUrl();
        var ODataURL = serverUrl + entitySet;
        var json = JSON.stringify(params);      //MUST CONVERT TO JSON STRING

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: ODataURL,
            data: json,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                if (onComplete != null)
                    onComplete(data.d.results);
            },
            error: function (XmlHttpRequest, textStatus, errorObject) {
                var msg = textStatus;
                try {
                    msg = JSON.parse(XMLHttpRequest.responseText).error.message.value;
                } catch (e) { }

                if (onError != null)
                    onError(msg);
            }
        });
    },
    GetServerUrl: function () {
        var serverUrl = '';
        if (typeof (Xrm) != 'undefined' && Xrm != null) {
            serverUrl = Xrm.Page.context.getServerUrl();
            //test that server name is not coming back instead of the domain name
            //otherwise we get a Cross-Origen (CORS) 400 error           
        }
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }

        return serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    },

}
The above script implements two main methods:

Method Name
Description
AddNote
This method handles the interaction with the Dynamics CRM web service. It takes the following parameters:

Name
Description
Params
JSON structure that contains the note information
entitySet
This is the name of the entity where the record needs to be added. For notes, the name is AnotationSet
onComplete
This is a callback handler
onError
This is a callback handler for errors

Note the following attributes on the request:

The Dynamic CRM web services are RESTFul. For the creation of a new note, we to set the verb to POST.

Since we pass a JSON structure we set the content and data types to JSON

The data parameter contains the JSON data in string format which is generated after calling the stringify function

GetServerUrl
This method resolves the server URL and current organization name.

TestNotes Script:

OGBIT.TestNotes = {
   AddNotes: function () {
      var self = OGBIT.TestNotes;
      var note = {};
      var ref = {};
      note.NoteText = "This is the content of the notes";
      note.Subject = "Note Unit test";
      ref.LogicalName = Xrm.Page.data.entity.getEntityName();//returns the entity name
      ref.Id = Xrm.Page.data.entity.getId();             //returns the primary id/guid
      note.ObjectId = ref;                              //associate the note to an entity
     OGBIT.NoteManager.AddNote(note, 'AnnotationSet', self.onComplete, self.onError); //AnnotationSet is the notes entity set 
    },
    onError: function (msg) {
        alert(msg)
    },
    onComplete: function (data) {
        alert(data);
    }
}

The above script creates the following JSON structures:

Name
Description
Note
This is the note object notation. It is created with the following attributes:

Name
Description
NoteText
This is the content for the note
Subject
This is the subject
ObjectId
This is the object associated to the notes. I.E. A note can be associated to an account or other custom entity that support notes.


ref
This is the associated object. It needs the following attributes:

Name
Description
LogicalName
This is the name of the entity
Id
This is the primary id (GUID)

These values can be fetched by using the Xrm client object model. It uses the current context to retrieve the entity information.


After creating the JSON references, the script uses the NoteManager method to post the request to the web services. The callback handlers are called after the web service call has completed. 



I hope these scripts can help you get more understanding of the Dynamics CRM web services and how to interact with them via JavaScript.