Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

How to get current user time on client side (JavaScript)

Recently I got requirement to fill-in field on a web resource with current user time (CRM settings should be took into account).

I use following code to implement requirement:
1. Retrieve user settings 2. Ask server to execute UtcTimeToLocalTime request with user time zone provided

This is code:
DateTimeHelper = {};

(function (DateTimeHelper, jQuery, $) {

    DateTimeHelper.GetUserLocalTime = function (date) {
        var userId = context().getUserId();
        var settings = getCurrentUserSettings(userId);
        var timeZoneCode = settings.TimeZoneCode;
        var dateTime = Teoco.DateTimeHelper.UtcTimeToLocalTime(timeZoneCode, date);
        return dateTime;
    };

    DateTimeHelper.UtcTimeToLocalTime = function (timeZoneCode, dateTime) {
        var req = getXhr();
        req.open("POST", getServicePath(), false);
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

        var xml =
            "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
            "  <s:Body>" +
            "    <Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
            "      <request i:type='b:LocalTimeFromUtcTimeRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
            "        <a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
            "          <a:KeyValuePairOfstringanyType>" +
            "            <c:key>TimeZoneCode</c:key>" +
            "            <c:value i:type='d:int' xmlns:d='http://www.w3.org/2001/XMLSchema'>" + timeZoneCode + "</c:value>" +
            "          </a:KeyValuePairOfstringanyType>" +
            "          <a:KeyValuePairOfstringanyType>" +
            "            <c:key>UtcTime</c:key>" +
            "            <c:value i:type='d:dateTime' xmlns:d='http://www.w3.org/2001/XMLSchema'>" + dateTime.toISOString() + "</c:value>" +
            "          </a:KeyValuePairOfstringanyType>" +
            "        </a:Parameters>" +
            "        <a:RequestId i:nil='true' />" +
            "        <a:RequestName>LocalTimeFromUtcTime</a:RequestName>" +
            "      </request>" +
            "    </Execute>" +
            "  </s:Body>" +
            "</s:Envelope>";

        req.send(xml);

        var date = null;

        if (req.status === 200) {
            var resultXml = req.responseXML;
            var dateString = $(resultXml).find("value").text()
            date = new Date(dateString);
        }
        else {
            alert("Failed to retrieve current user local time");
            throw "Failed to retrieve current user local time";
        }

        return date;
    };

    function getCurrentUserSettings(userId) {
        var request = "/UserSettingsSet?$filter=SystemUserId eq guid'" + userId + "'";

        var settings = null;

        callOData(request,
            function (data) {
                if(data != null && data.results != null && data.results.length != 0)
                {
                    settings = data.results[0];
                }
            },
            function (xhr) {
            });

        if (settings == null) {
            alert("Failed to load current user settings");
            throw "Failed to load current user settings";
        }

        return settings;
    }

    function callOData(request, onSuccess, onError) {
        var req = getXhr();
        req.open("GET", getODataPath() + request, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.send();

        if (req.status === 200) {
            onSuccess(JSON.parse(req.responseText).d);
        }
        else {
            onError(req);
        }
    }

    function getServicePath() {
        return getClientUrl() + "/XRMServices/2011/Organization.svc/web";
    }

    function getODataPath() {
        return getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
    }

    function getClientUrl() {
        var serverUrl = typeof context().getClientUrl !== "undefined" ? context().getClientUrl() : context().getServerUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        return serverUrl;
    }

    function context() {
        var oContext;
        if (typeof window.GetGlobalContext != "undefined") {
            oContext = window.GetGlobalContext();
        }
        else {
            if (typeof Xrm != "undefined") {
                oContext = Xrm.Page.context;
            }
            else if (typeof window.parent.Xrm != "undefined") {
                oContext = window.parent.Xrm.Page.context;
            }
            else {
                throw new Error("Context is not available.");
            }
        }
        return oContext;
    }

    function getXhr() {
        if (XMLHttpRequest) {
            return new XMLHttpRequest();
        }
        try {
            return new ActiveXObject('MSXML2.XMLHTTP.6.0');
        } catch (e) {
            try {
                return new ActiveXObject('MSXML2.XMLHTTP.3.0');
            } catch (e) {
                alert('This browser is not AJAX enabled.');
                return null;
            }
        }
    }

})(DateTimeHelper, jQuery, jQuery);
And this is usage example:
var today = Teoco.DateTimeHelper.GetUserLocalTime(new Date());

HOW TO: Change fileld requirement level, Bypass valiation in MS CRM 2011

MS CRM 2011 provides api to change requiremnt level of fields of the form (this is a new feature of crm 2011).

Xrm.Page.getAttribute("my_fieldname").setRequiredLevel("none");
Xrm.Page.getAttribute("my_fieldname").setRequiredLevel("required");
Xrm.Page.getAttribute("my_fieldname").setRequiredLevel("recommended");

If you need to bypass validation during saving of the form use function below. Call it during form load. Note! This script is not supported by Microsoft CRM SDK and it could couse errors. I used it on lead form without any trouble.

function BypassValidation()
{
$get("crmForm").BypassValidation = true;
}

HOW TO: Show/Hide notifications (warnings) in MS CRM 2011

This post describes:
  1. How to disable notifications on the form
  2. How to show custom notification (info, warning, error)
  3. How to clean notification area
All scripts below require jQuery.
Most frequently I use these scripts to get rid of warning “The following error occurred: Missing Price List” and show custom messages

MS CRM 2011: My first experience. Adding OnLoad event script.

Today I've started studing functionality of new MS CRM 2011. I want to descover client scripting first and today I've added OnLoad event script. I want to share steps I've made to add script on the form.

HOW TO: Resize MS CRM forms to fit screen size


Read this post if you want one wiondow or all to fit screan size.

If you need only one form to fit screan size you can add following code in the OnLoad event:
    window.moveTo(0, 0);
    window.resizeTo(screen.availWidth, screen.availHeight);
  

Three easy steps are needed to make all CRM 4.0 forms to fit screen size:
  1. Locate global.js file ([Path to Microsoft Dynamics CRM folder]\_static\_common\scripts\global.js) and open it

  2. Locate safeWindowShowModelessDialog function and change it as shown below:



  3. Locate safeWindowOpen function and change it as shown below:




Code needs to be inserted in safeWindowOpen and safeWindowShowModelessDialog:
    if(windowOpened!=null)
    {
    windowOpened.window.moveTo(0, 0);
    windowOpened.window.resizeTo(screen.availWidth, screen.availHeight);
    }