04 April 2013

Get The CRM 2011 Timezone Settings For Current User With JavaScript

Sometimes it's useful to know the current user's timezone settings, for instance DateTime results in ODATA will be UTC so you may need to know how that should appear to the user. There are a bunch of blogs/user group posts about working out the summertime offset which doesn't make sense in my testing, if anybody can explain it and give examples I'd be grateful. Also a word of caution I've also noticed that if the Windows and CRM timezone settings are different it can also cause you some fun and games. Anyways enough of that here's the JavaScript to get the user's timezone settings:
GetUserTimeZoneDetails = function ()
{
 
 var ODataPath = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc";
 var filter = "/UserSettingsSet(guid'" + Xrm.Page.context.getUserId() + "')";
 
 var userSettingReq = new XMLHttpRequest();
 userSettingReq.open('GET', ODataPath + filter, false);
 userSettingReq.setRequestHeader("Accept", "application/json");
 userSettingReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 userSettingReq.send(null);

 var userSetting = this.JSON.parse(userSettingReq.responseText).d;
 var timeZoneBias = 0;
 try
 {
  timeZoneBias = userSetting.TimeZoneBias;
 }
 catch (e)
 {
  timeZoneBias = 0;
 }

 var timeZoneDayLightBias = 0;

 try
 {
  timeZoneDayLightBias = userSetting.TimeZoneDaylightBias;
 }
 catch (e)
 {
  timeZoneDayLightBias = 0;
 }
 
 return [timeZoneBias, timeZoneDayLightBias];
}
The function returns an array containing two elements the timezone bias and timezone daylight bias. The timezonebias is the local time zone adjustment for the user. System calculated based on the time zone selected. The timezonedaylightbias is the local time zone daylight adjustment for the user. System calculated based on the time zone selected. The SDK has details about other user settings that can be retrieved in the same way as above, see User Settings MetaData

03 April 2013

Using The CRM 2011 SOAP Endpoint

When we retrieve data from CRM 2011 through JavaScript more often than not we use the REST endpoints but there are times when you may decide that the SOAP endpoint is going to be a better tool for the job. This article isn't going to dictate which endpoint you use, there is an article on MSDN which outlines the benefits of each: Use Web Service Data in Web Resources (REST and SOAP Endpoint).

If you want to get at CRM data through the SOAP endpoint then here some steps that will get you to where you want to be:

1. The SDK has a code sample called SOAPLogger, after downloading the SDK navigate to samplecode\cs\client\soaplogger\ and open the project in Visual Studio
2. We now need to add some code that we'll use to generate the SOAP envelope. In this sample it will retrieve a contact record returning the first name, last name, and email address. Open up SOAPLogger.cs and add the following to the Run Method:

Guid contactId = new Guid("[A Valid GUID goes here]");

RetrieveRequest retrieveContact = new RetrieveRequest();
retrieveContact.ColumnSet = new ColumnSet(new string[] { "firstname", "lastname", "emailaddress1" });
retrieveContact.Target = new EntityReference("contact", contactId);

slos.Execute(retrieveContact);


3. Go ahead and run the project, a command prompt appears and you'll need to provide the connection information to the CRM server you want to connect to. After the code has executed you're prompted to "Press (Enter) to exit."

4. A text file has been created in the execution folder called "output.txt", open this with notepad.

5. We are interested in the HTTP REQUEST section, specifically the soap envelope, which we'll copy (see highlighted text in screenshot):


6. Now we're ready to write some JavaScript, the request variable is going to contain the SOAP envelope that we copied in the previous step:
var serverUrl = "[CRM Server Url]";

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", serverUrl() + "/XRMServices/2011/Organization.svc/web", false);
xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");

var request = "";
request += '';
request += '  ';
request += '    ';
request += '      ';
request += '        ';
request += '          ';
request += '            Target';
request += '            ';
request += '              e183560d-2680-e211-bc33-005056ba9f90';
request += '              contact';
request += '              ';
request += '            ';
request += '          ';
request += '          ';
request += '            ColumnSet';
request += '            ';
request += '              false';
request += '              ';
request += '                firstname';
request += '                lastname';
request += '                emailaddress1';
request += '              ';
request += '            ';
request += '          ';
request += '        ';
request += '        ';
request += '        Retrieve';
request += '      ';
request += '    ';
request += '  ';
request += '';

xmlhttp.send(request);

7. xmlhttp.responseXML.xml is going to contain the response XML from the web service call. To make like easier I've written a method that you can pass the XML to, along with the field name, which will return the value (e.g. GetResponse(xmlhttp.responseXML.xml, "firstname"):

GetResponse = function (responseXML, attributename)
{
    var returnValue = "";

    try
    {
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(responseXML);
        
        var x = xmlDoc.getElementsByTagName("a:KeyValuePairOfstringanyType");

        for (i = 0; i < x.length; i++)
        {
            if (x[i].childNodes[0].text == attributename)
            {
                returnValue = x[i].childNodes[1].text;
                break;
            }
        }
    }
    catch (e)
    {
        returnValue = "";
    }
    return returnValue;
}



13 February 2013

SQL Joins



SQL Joins


I'm always at a loss when asked to explain the differences between the different types of (SQL) joins. I know what I need to use but in my muddled mind can't ever explain why. This post should help to explain the differences for those that don't know and help remind those that do.

Joins are either inner or outer, outer can be full outer, left outer, or right outer. Let’s start with a couple of tables to help visualise what each join will do.

Table A

User Id
Name
1
Adrian Williams
2
Steve Sidwell
3
James Harper
4
Jamie Cureton
5
Nicky Forster
6
Barry Hunter
7
Jimmy Quinn
Table B

User Id
Login
3
Jharper
4
Jcureton
5
nforster
6
Bhunter
7
Jquinn
8
Scoppell
9
brodgers

Assume that all queries are asked to return user id (from Table A), name, and login.
Each of the joins will return the following

Left Outer Join

The left outer join will return all records from Table A and values from Table B where they exist, otherwise a null is returned.

TSQL:
select
      tablea.userid as userid,
      name,
      login
from
      TableA
left outer join
      TableB on TableA.userid = TableB.userid


Results:
User Id
Name
Login
1
Adrian Williams
NULL
2
Steve Sidwell
NULL
3
James Harper
jharper
4
Jamie Cureton
jcureton
5
Nicky Forster
nforster
6
Barry Hunter
bhunter
7
Jimmy Quinn
jquinn

Right Outer Join

The right outer join will return all records from Table B and values from Table A where they exist, otherwise a null is returned.


TSQL:
select
      tablea.userid as userid,
      name,
      login
from
      TableA
right outer join
      TableB on TableA.userid = TableB.userid

Results:
User Id
Name
Login
3
James Harper
jharper
4
Jamie Cureton
jcureton
5
Nicky Forster
nforster
6
Barry Hunter
bhunter
7
Jimmy Quinn
jquinn
NULL
NULL
scoppell
NULL
NULL
brodgers

Full Outer Join

The full outer join will return all records from Table A and Table B, where there isn’t a corresponding record in null will be returned.

TSQL:
select
      tablea.userid as userid,
      name,
      login
from
      TableA
Full outer join
      TableB on TableA.userid = TableB.userid


Results:
User Id
Name
Login
1
Adrian Williams
NULL
2
Steve Sidwell
NULL
3
James Harper
jharper
4
Jamie Cureton
jcureton
5
Nicky Forster
nforster
6
Barry Hunter
bhunter
7
Jimmy Quinn
jquinn
NULL
NULL
scoppell
NULL
NULL
brodgers

Inner Join

The inner join will only return data from rows where there is a match in both Table A and Table B.

TSQL:
select
      tablea.userid as userid,
      name,
      login
from
      TableA
inner join
      TableB on TableA.userid = TableB.userid


Results:
User Id
Name
Login
3
James Harper
jharper
4
Jamie Cureton
jcureton
5
Nicky Forster
nforster
6
Barry Hunter
bhunter
7
Jimmy Quinn
jquinn