CRM 2013 Javascript Block Save

0 comments


Script:

function My_PreventSaveFunction(eContext, Message) {
        alert(Message);
        eContext.getEventArgs().preventDefault();
}

CRM 2013 Javascript Filter Custom Lookup View Field (PreFiltering Method)

0 comments


Issues:

Changes in category effect custom filtering, then the lookup display on form will corrupt but when u click on lookup more its ok.

Script:

var filter = '';

function FilterListingViewCategory(Value) {
    filter = "<filter type='and'>" +
              "<condition attribute='statecode' operator='eq' value='0' />" +
              "<condition attribute='vwlzs_category' operator='in'>" +
                "<value>" + RegistrationId + "</value>" +
              "</condition>" +
         "</filter>";

    preFilterLookupCategory(filter);
}

function preFilterLookupCategory(filter) {

    Xrm.Page.getControl("vwlzs_aidcategorylk").addPreSearch(function () {
        addLookupFilterCategory(filter);
    });
}

function addLookupFilterCategory(filter) {

    Xrm.Page.getControl("vwlzs_aidcategorylk").addCustomFilter(filter);
}

CRM 2013 Javascript Filter Custom Lookup View Field (FetchXML)

0 comments


Issues:

This part doesn't work when user click on lookup for more because i'm unable to set the default view fo the lookup. The user need to select the custom view by their own.

Script:

function FilterListingViewAidCategory(Value) {

    var RegistrationId = Xrm.Page.getAttribute("vwlzs_asnafcategory").getValue();
    if (RegistrationId == null && Value != null) {
        RegistrationId == Value;
    }
    var entityNumber = GetObjectTypeCode("vwlzs_aidsapplication");

    var FetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                      "<entity name='vwlzs_category'>" +
                        "<attribute name='vwlzs_categoryid' />" +
                        "<attribute name='vwlzs_name' />" +
                        "<attribute name='createdon' />" +
                        "<order attribute='vwlzs_name' descending='false' />" +
                        "<filter type='and'>" +
                          "<condition attribute='statecode' operator='eq' value='0' />" +
                          "<condition attribute='vwlzs_categoryasnaf' operator='in'>" +
                            "<value>" + RegistrationId + "</value>" +
                          "</condition>" +
                        "</filter>" +
                      "</entity>" +
                    "</fetch>";

    var layoutXml = "<grid name='resultset' object='10038' jump='vwlzs_name' select='1' preview='1' icon='1'>" +
                        "<row name='result' id='vwlzs_categoryid'>" +
                          "<cell name='vwlzs_name' width='300' />" +
                          "<cell name='createdon' width='150' />" +
                        "</row>" +
                      "</grid>";

    var viewId = guid();
    var viewDisplayName = "Filtered Based On Category";


    Xrm.Page.getControl("vwlzs_aidcategorylk").addCustomView(viewId, "vwlzs_category", viewDisplayName, FetchXML, layoutXml, true);
}


CRM 2013 Javascript Check CRM User Role in System

0 comments


Script:

function CheckorNotInterBranch() {
    var EntityId = Xrm.Page.ui.getFormType();
    if (EntityId == 1) {
        //Security.UserInRole.checkUserInRole(["HQ Staff", "System Customizer", "Custom Role Name"], function () {
        Security.UserInRole.checkUserInRole(["HQ Staff"], function () {
            //alert("valid"); // The user is in one of the specifed roles.
            Xrm.Page.getAttribute("vwlzs_interbranch").setValue(true);
        },
        function () {
            //alert("invalid"); // The user is not in one of the specifed roles.
            Xrm.Page.getAttribute("vwlzs_interbranch").setValue(false);
        });
    }
    //check new form
    // Check user role when user role = HQ Staff then inter branch = yes
    //var UserRoles = Xrm.Page.context.getUserRoles();
    // Check User role when user role = branch staff then inter branch = no
}

//If the Security namespace object is not defined, create it.
if (typeof (Security) == "undefined")
{ Security = {}; }
// Create Namespace container for functions in this library;
if (typeof (Security.UserInRole) == "undefined") {
    Security.UserInRole = {
        isInRole: null,
        roleIdValues: [],
        validFunction: null,
        invalidFunction: null,
        checkRoles: [],
        checkUserInRole: function (roles, validFunc, invalidFunc) {
            validFunction = validFunc;
            invalidFunction = invalidFunc;
            checkRoles = roles;
            Security.UserInRole.getAllowedSecurityRoleIds();
        },
        getAllowedSecurityRoleIds: function () {
            var filter = "";
            for (var i = 0; i < checkRoles.length; i++) {
                if (filter == "") {
                    filter = "Name eq '" + checkRoles[i] + "'";
                }
                else {
                    filter += " or Name eq '" + checkRoles[i] + "'";
                }
            }
            Security.UserInRole.querySecurityRoles("?$select=RoleId,Name&$filter=" + filter);
        },
        validateSecurityRoles: function () {
            switch (Security.UserInRole.isInRole) {
                //If the user has already been discovered in role then call validFunc
                case true:
                    validFunction.apply(this, []);
                    break;
                default:
                    var userRoles = Xrm.Page.context.getUserRoles();
                    for (var i = 0; i < userRoles.length; i++) {
                        var userRole = userRoles[i];
                        for (var n = 0; n < Security.UserInRole.roleIdValues.length; n++) {
                            var role = Security.UserInRole.roleIdValues[n];
                            if (userRole.toLowerCase() == role.toLowerCase()) {
                                Security.UserInRole.isInRole = true;
                                // Call function when role match found
                                validFunction.apply(this, []);
                                return true;
                            }
                        }
                    }
                    // Call function when no match found
                    invalidFunction.apply(this, []);
                    break;
            }
        },
        querySecurityRoles: function (queryString) {
            var req = new XMLHttpRequest();
            var url = "";
            // Try getClientUrl first (available post Rollup 12)
            if (Xrm.Page.context.getClientUrl) {
                url = Xrm.Page.context.getClientUrl();
            }
            else {
                url = Xrm.Page.context.getServerUrl();
            }
            req.open("GET", url + "/XRMServices/2011/OrganizationData.svc/RoleSet" + queryString, true);
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.onreadystatechange = function () {
                if (this.readyState == 4 /* complete */) {
                    req.onreadystatechange = null; //Addresses memory leak issue with IE.
                    if (this.status == 200) {
                        var returned = window.JSON.parse(this.responseText).d;
                        for (var i = 0; i < returned.results.length; i++) {
                            Security.UserInRole.roleIdValues.push(returned.results[i].RoleId);
                        }
                        if (returned.__next != null) {
                            //In case more than 50 results are returned.
                            // This will occur if an organization has more than 16 business units
                            var queryOptions = returned.__next.substring((url + "/XRMServices/2011/OrganizationData.svc/RoleSet").length);
                            Security.UserInRole.querySecurityRoles(queryOptions);
                        }
                        else {
                            //Now that the roles have been retrieved, try again.
                            Security.UserInRole.validateSecurityRoles();
                        }
                    }
                    else {
                        var errorText;
                        if (this.status == 12029)
                        { errorText = "The attempt to connect to the server failed."; }
                        if (this.status == 12007)
                        { errorText = "The server name could not be resolved."; }
                        try {
                            errorText = window.JSON.parse(this.responseText).error.message.value;
                        }
                        catch (e)
                        { errorText = this.responseText }
                    }
                }
            };
            req.send();
        },
        __namespace: true
    };
}


CRM 2013 Javascript Disable form.

0 comments


Script:

disableFormFields = function (onOff) {
    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
} //Function to disable all the field in the form// true/false

doesControlHaveAttribute = function (control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
} //Sub disableFormFields// Check the form have control like iframe, webresource or subgrid

function onload() {
     disableFormFields(true);
}

CRM 2013 Javascript Calculate Age Based On Date of Birth

0 comments


Script:

function CalculateAge() {

    var DOB = Xrm.Page.getAttribute("vwlzs_dateofbirth").getValue();
    var todadate = new Date();

    if (DOB < todadate) {

        if (DOB != null) {

            var d = new Date();
            var n = d.getFullYear();
            var TotalAge = n - DOB.getFullYear();
            Xrm.Page.getAttribute("vwlzs_age").setValue(parseInt(TotalAge));
        }
        else {
            Xrm.Page.getAttribute("vwlzs_age").setValue(null);
        }
    }
    else {
        alert("No future date allow!");
    }
}

CRM 2013 Javascript Populate Date of Birth and Age from NRIC/MyKad

0 comments


Script:

function PopulateDateofBirthAndAge(NRICValue) {
    var var1 = value.substring(0, 2);
    var var2 = value.substring(2, 4);
    var var3 = value.substring(4, 6);

    var d = new Date();
    d.setDate(var3);
    d.setMonth(var2);
    d.setYear(var1);

    NRIC_TextInput(value, var1, var2, var3);
}

function NRIC_TextInput(id, yearid, monthid, dayid) {
    var value = id;

    if (value && value.length == 12) {
        var isValid = true;
        var n = value.split("");
        var Year = parseFloat("20" + n[0] + n[1]);
        var Month = parseFloat(n[2] + n[3]);
        var Day = parseFloat(n[4] + n[5]);
        var Now = new Date();
        var Age = 0;

        var sMonth = "";
        if (Month < 1 || Month > 12) isValid = false;
        if (isValid) {
            if (Year > Now.getFullYear()) {
                Year = Year - 100;
                //Age check on month and date reach ?
                Age = Now.getFullYear() - Year;
            }
            else {
                //Age check on month and date reach ?
                Age = Now.getFullYear() - Year;
            }
            switch (Month) {
                case 1:
                    sMonth = "January";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 2:
                    sMonth = "February";
                    if (Year % 4 == 0) {
                        if (Day > 29 || Day <= 0) isValid = false;
                    } else {
                        if (Day > 28 || Day <= 0) isValid = false;
                    }
                    break;
                case 3:
                    sMonth = "March";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 4:
                    sMonth = "April";
                    if (Day > 30 || Day <= 0) isValid = false;
                    break;
                case 5:
                    sMonth = "May";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 6:
                    sMonth = "June";
                    if (Day > 30 || Day <= 0) isValid = false;
                    break;
                case 7:
                    sMonth = "July";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 8:
                    sMonth = "August";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 9:
                    sMonth = "September";
                    if (Day > 30 || Day <= 0) isValid = false;
                    break;
                case 10:
                    sMonth = "October";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                case 11:
                    sMonth = "November";
                    if (Day > 30 || Day <= 0) isValid = false;
                    break;
                case 12:
                    sMonth = "December";
                    if (Day > 31 || Day <= 0) isValid = false;
                    break;
                default:
                    isValid = false;
                    break;
            }
        }

        if (isValid) {
            Xrm.Page.getAttribute("vwlzs_age").setValue(Age);
            var DOB = new Date(Year, monthid - 1, dayid, 0, 0, 0);
            Xrm.Page.getAttribute("vwlzs_dateofbirth").setValue(DOB);
        } else {
            alert("Invalid NRIC Number.");
        }

    }
    else {
        alert("Invalid NRIC Number.");
    }
}

CRM 2013 Javascript Define Gender Through NRIC/MyKad

0 comments


Script:

function DefineMaleFemale() {
    var NRIC = Xrm.Page.getAttribute("vwlzs_identificationnum").getValue();

    if (NRIC != null) {
        var last = NRIC.charAt(NRIC.length - 1);

        if (isEven(last) == true) {
            Xrm.Page.getAttribute("vwlzs_gender").setValue(true); //Female
        }
        else {
            Xrm.Page.getAttribute("vwlzs_gender").setValue(false); //Male
        }
    }
}

function isEven(value) {
    if (value % 2 == 0)
        return true;
    else
        return false;
}

CRM 2013 Javascript Refresh form

0 comments


Script:

function TriggerSubmit() {
Xrm.Page.data.save().then(successCallback, errorCallback);
}

function successCallback() {
    Xrm.Page.data.setFormDirty(false);
    var Id = Xrm.Page.data.entity.getId();
    Xrm.Utility.openEntityForm("vwlzs_register", Id);
}

function errorCallback(attr1, attr2) {

}


CRM 2013 Javacript Validate Integer

0 comments


Script:

function CheckInteger(Field) {
    var Result = Xrm.Page.getAttribute(Field).getValue();

    if (isInt(Result)) {
        Xrm.Page.getAttribute(Field).setValue(Result);
    }
    else {
        alert("Input is not numeric")
        Xrm.Page.getAttribute(Field).setValue(null);
    }
}

function isInt(value) {
    return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10));

}

CRM 2013 Javascript Validate Symbol

0 comments


Script:

function validateSymbol(Field) {
    var TCode = Xrm.Page.getAttribute(Field).getValue();

    if (/[^a-zA-Z0-9\-\/]/.test(TCode)) {
        alert("Input is not alphanumeric");
        Xrm.Page.getAttribute(Field).setValue(null);
    }
}

CRM 2013 Remove all the subgrid add button

0 comments


Call it during On load (with certain condition) then all the sub grid add button in the form will be hidden.

Script:

var intervalId;

function makeReadOnly() {
    try {
        var subgridsLoaded = false;

        Xrm.Page.ui.controls.get().forEach(function (control, index) {
            if (control.setDisabled && Xrm.Page.ui.getFormType() != 3) {
                control.setDisabled(true);
            }
            else {
                // removeAddButtonFromSubGrid(control);
                // subgridsLoaded = true; 
            }
        });

        if ($("div[id$='_crmGridTD']").length > 0 && !subgridsLoaded) {
            intervalId = setInterval(function () {
                var subgridsArr = Xrm.Page.getControl(function (control, index) {
                    return control.getControlType() == 'subgrid';
                });
                subgridsArr.forEach(function (control, index) {
                    removeButtonsFromSubGrid(control);
                });
            }, 500);
        }
    }

    catch (e) {
        alert("makeReadOnly() Error: " + e.message);
    }
}

function removeButtonsFromSubGrid(subgridControl) {
    if (intervalId) {
        $('#' + subgridControl.getName() + '_addImageButton').css('display', 'none');
        $('#' + subgridControl.getName() + '_openAssociatedGridViewImageButton').css('display', 'none');
        clearInterval(intervalId);
    }
}

How to remove TFS lock of other user

0 comments


Problem:

Window corrupt and need to be format and install with new window with different PC name. After format notice that in Team Foundation Server (TFS) certain file is lock from editing by old PC name.

Solution:

From within Visual Studio 2012(and 2013):

File -> Source Control -> Advanced -> Workspaces...

In the dialog that came up, I checked "Show remote workspaces" and the locked workspace came up in the window. I then selected it and clicked "Remove".

The locked file is release.