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

Friday, January 28, 2011

Areas of interest

These are the areas we will cover in our posts:

Microsoft Dynamics CRM
Microsoft Dynamics NAV
Microsoft Dynamics AX
Microsoft SharePoint
Microsoft Office
Microsoft SQL Server
C#
WPF
WCF
Silverlight
ASP
HTML
JavaScript
.NET Framework
Windows 7
Windows Mobile
Windows Phone 7
Visual Studio 2010
Microsoft Surface
Project Management
Product Management
PR
Marketing

Wednesday, January 26, 2011

Generate a new Guid in JavaScript

As easy as that :)

// Generate new Guid

function Hexa4()
{
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function GenerateGuid()
{
return (Hexa4()+Hexa4()+"-"+Hexa4()+"-"+Hexa4()+"-"+Hexa4()+"-"+Hexa4()+Hexa4()+Hexa4()).toUpperCase();
}

// USE
var guid = GenerateGuid();
alert(guid);

Create a custom filtered lookup view in runtime - CRM 2011

Starting CRM 2011 you can filter a certain lookup view based on related entities or other system/custom views. But sometimes this is not enough. For example, if you wanna make a custom filtered view, that uses several filters, you can use the following approach.

Starting scenario (all of the completed lookup fields will be used as filters):


// *** ALL IN 1 CODE ***
// Structs
var FilterBy = MakeStruct("SchemaName Operator Value");
var ViewColumn = MakeStruct("SchemaName Width");

// Advanced Filtered Lookup
function AdvancedFilteredLookup(lookupSchemaName, viewId, entityName, primaryKeyName, primaryFieldName, viewDisplayName, filterBy, orderBy, viewColumns)
{
var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='" + entityName + "'>" +
"<attribute name='" + primaryFieldName + "' />" +
"<order attribute='" + orderBy + "' descending='false' />" +
"<filter type='and'>" +
"<filter type='and'>";
for(var i=0; i< filterBy.length; i++)
fetchXml += "<condition attribute='" + filterBy[i].SchemaName + "' operator='" + filterBy[i].Operator + "' value='" + filterBy[i].Value + "' />";
fetchXml += "</filter></filter></entity></fetch>";

var layoutXml = "<grid name='resultset' " +
"object='1' " +
"jump='name' " +
"select='1' " +
"icon='1' " +
"preview='1'>" +
"<row name='result' " +
"id='" + primaryKeyName + "'>";
for(var i=0; i< viewColumns.length; i++)
layoutXml += "<cell name='" + viewColumns[i].SchemaName + "' width='" + viewColumns[i].Width.toString() + "' />";
layoutXml += "</row></grid>";

try {
var lookupControl = Xrm.Page.ui.controls.get(lookupSchemaName);
lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
}
catch(err) {
}
}

// USE - we gonna create a custom filtered lookup view for the new_productid lookup field
// Note: this function should be called on the OnChange() event of all the filter-fields (for example: new_type1id)
function FilterProducts()
{
try {
// Parameters
var customViewId = "{FD140AAF-4DF4-11DD-BD17-0019B9312238}"; // new id
var customViewName = "Type Filtered Products";
var lookupFieldName = "new_productid";
var entityName = "product";
var primaryKeyName = "productid";
var primaryFieldName = "name";
var orderBy = "name";

// Generate Filters
var type1id = crmForm.all.item("nov_type1id").DataValue != null ? crmForm.all.item("nov_type1id").DataValue[0].id : null;
var type2id = crmForm.all.item("nov_type2id").DataValue != null ? crmForm.all.item("nov_type2id").DataValue[0].id : null;
var type3id = crmForm.all.item("nov_type3id").DataValue != null ? crmForm.all.item("nov_type3id").DataValue[0].id : null;
var type4id = crmForm.all.item("nov_type4id").DataValue != null ? crmForm.all.item("nov_type4id").DataValue[0].id : null;
var clientneedid = crmForm.all.item("nov_clientneedid").DataValue != null ? crmForm.all.item("nov_clientneedid").DataValue[0].id : null;
var vendorid = crmForm.all.item("nov_vendorid").DataValue != null ? crmForm.all.item("nov_vendorid").DataValue[0].id : null;
var filters = new Array();
var index = 0;
if(type1id != null)
filters[index++] = new FilterBy("new_type1id", LogicalOperator.Eq, type1id);
if(type2id != null)
filters[index++] = new FilterBy("new_type2id", LogicalOperator.Eq, type2id);
if(type3id != null)
filters[index++] = new FilterBy("new_type3id", LogicalOperator.Eq, type3id);
if(type4id != null)
filters[index++] = new FilterBy("new_type4id", LogicalOperator.Eq, type4id);
if(clientneedid != null)
filters[index++] = new FilterBy("new_clientneedid", LogicalOperator.Eq, clientneedid);
if(vendorid != null)
filters[index++] = new FilterBy("nov_vendorid", LogicalOperator.Eq, vendorid);

// View Columns
var viewColumns = [new ViewColumn("name", 200), new ViewColumn("productnumber", 100), new ViewColumn("new_type1id", 100), new ViewColumn("new_type2id", 100), new ViewColumn("new_type3id", 100), new ViewColumn("new_type4id", 100), new ViewColumn("new_clientneedid", 100), new ViewColumn("nov_vendorid", 100)];

// Create Dynamics View
AdvancedFilteredLookup(lookupFieldName, customViewId, entityName, primaryKeyName, primaryFieldName, customViewName, filters, orderBy, viewColumns);

// Clear Previous Product Value
crmForm.all.item(lookupFieldName).DataValue = null;
}
catch(err) {
}
}

And now, the custom filtered lookup view for the new_productid lookup field will look like this:


Hope you'll find this article useful.

P.S.: In my opinion, filtering a lookup this way is a lot more efficient than altering the lookupsingle.aspx file (the unsupported method used in CRM 4.0) ;)

Creating records in CRM 2011 using JavaScript

Using the CRM Web Service, you can create new entity records, just using JavaScript. The following code demonstrates this:

// Make Struct
function MakeStruct(names) {
var names = names.split(' ');
var count = names.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[names[i]] = arguments[i];
}
}
return constructor;
}


// CRM Field Struct
var CRMField = MakeStruct("SchemaName Value");

// Call Crm Service
function CallCrmService(soapBody, method)
{
try {
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", '/mscrmservices/2007/CrmService.asmx', false);
xmlHttpRequest.setRequestHeader("SOAPAction", 'http://schemas.microsoft.com/crm/2007/WebServices/' + method);
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"
<soap:Envelope xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'>" +
GenerateAuthenticationHeader() + "<soap:Body>" + soapBody + "</soap:Body></soap:Envelope>";
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
var errorCount = resultXml.selectNodes('//error').length;

if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);

return null;
}

return resultXml;
}
catch(err) {
}

return null;
}

// Create Record
function CreateRecord(entityName, fields)
{
try {
var resultArray = new Array();
var attributesList = '';

for(var i = 0; i < fields.length; i++)
attributesList += "<" +
fields[i].SchemaName + ">" + fields[i].Value + "</"+fields[i].SchemaName+">";
}

var xml = "
<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'><entity xsi:type='"+entityName+"'>" + attributesList + "</entity></Create>";
var resultXml = CallCrmService(xml, 'Create');

if (resultXml) {
var newid = resultXml.selectSingleNode('//CreateResult').nodeTypedValue;
return newid;
}
}
catch(err) {
}

return null;

}

// USE
// Create new Contact
function CreateContact()
{
var fields = [new CRMField('firstname', 'Cornel'), new CRMField('lastname, 'Croitoriu')];
return CreateRecord('contact', fields); // return new contact id
}

// Create new Annotation
function CreateAnnotation(parentEntityName, parentEntityId, title, text)
{
var fields = [new CRMField('objecttypecode', parentEntityName), new CRMField('objectid', parentEntityId), new CRMField('subject', title), new CRMField('notetext', text), new CRMField('isdocument', false), new CRMField("mimetype", "text/html")];
return CreateRecord('annotation', fields); // return new note id
}

// Example
CreateAnnotation('opportunity', 'FD140AAF-4DF4-11DD-BD17-0019B9312238', 'dynamic generated note', 'text goes here...');

Set a lookup value in CRM 2011

// Sets the lookup value for a certain field
function SetLookupValue(fieldName, id, name, entityType) {
if(fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;

Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}

// USE
SetLookupValue("new_blogid", "{FD140AAF-4DF4-11DD-BD17-0019B9312238}", "CRM Stuff", "new_blog");

JavaScript structures

Here's a brief example of how to create structures in JavaScript. We'll use this function a lot from now on in our code.

// Make Struct
function MakeStruct(names) {
var names = names.split(' ');
var count = names.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[names[i]] = arguments[i];
}
}
return constructor;
}

// Use
// Declaring the struct
var Person = MakeStruct("ID FirstName LastName Email");
// Instance
var person1 = new Person(21, "Cornel", "Croitoriu", "cscmediadesign@yahoo.com");

Hope you'll find this useful ;)

Tuesday, January 25, 2011

CRM 2011 Custom Form Button



Using some of the basic DOM vs JavaScript capabilities, you can use the following code to dynamically generate a custom button for your CRM Form in Microsoft Dynamics CRM 2011 (scroll to the end of this post to see an example of how to use it). The button will look just like the ones in the toolbar.
All you need is a random CRM field (the type doesn't matter) to host the button (the original field content will be hidden). Also, you'll need a custom function to pass for the onclick event.
Note: the image you use for the button must be placed inside the %programfiles%\Microsoft Dynamics CRM\CRMWeb\_imgs\ico folder.

The final output looks like this:




And... here's the code masterpiece :)...

// CODE

// Create Dynamic Button for CRM 5
function CreateButtonCRM5(fieldName, buttonText, buttonWidth, iconName, clickEvent)
{
functiontocall=clickEvent;
crmForm.all.item(fieldName + "_c").style.display = "none";

var li = document.createElement("LI");
li.setAttribute('id', fieldName + 'LI');
li.setAttribute('className', 'ms-crm-Menu');
li.setAttribute('title', buttonText);
li.setAttribute('onclick', functiontocall);
li.setAttribute('onmousedown', push_custom_button);
li.setAttribute('onmouseup', release_custom_button);
li.style.width=buttonWidth;
li.style.cursor="hand";
li.style.textAlign="center";
li.style.overflow="hidden";

var span = document.createElement("span");
span.setAttribute('className', 'ms-crm-Menu-Label');
span.setAttribute('id', fieldName + 'Span');
span.style.cursor = "hand";
li.appendChild(span);
li.onmouseover = function() { span.setAttribute('className', 'ms-crm-Menu-Label-Hovered'); }
li.onmouseout = function() { span.setAttribute('className', 'ms-crm-Menu-Label'); }

var a = document.createElement("a");
a.setAttribute('id', fieldName + 'A');
a.setAttribute('className', 'ms-crm-Menu-Label');
a.onclick = function() { return false; }
a.setAttribute('target', '_self');
a.setAttribute('href', 'javascript:onclick();');
a.style.cursor = "hand";
span.appendChild(a);

var img = document.createElement("img");
img.setAttribute('id', fieldName + 'Img');
img.setAttribute('className', 'ms-crm-Menu-ButtonFirst');
img.setAttribute('src', '/_imgs/ico/' + iconName);
img.style.cursor = "hand";

var span2 = document.createElement("span");
span2.setAttribute('id', fieldName + 'Span2');
span2.setAttribute('className', 'ms-crm-MenuItem-TextRTL');
span2.innerText = buttonText;
span2.style.cursor = "hand";
a.appendChild(img);
a.appendChild(span2);

removeChildNodes(crmForm.all.item(fieldName + "_d"));
crmForm.all.item(fieldName + "_d").appendChild(li);
}

function push_custom_button()
{
window.event.srcElement.style.marginLeft="1px";
window.event.srcElement.style.marginTop="1px";
}

function release_custom_button()
{
window.event.srcElement.style.marginLeft="0px";
window.event.srcElement.style.marginTop="0px";
}

// USE
function CustomClickFunction()
{
alert("your code goes here...");
}

// Create the button, using the new_custombutton field as a container
CreateButtonCRM5('new_custombutton', 'Custom Button','100 px', '16_cancel.png', CustomClickFunction);


BONUS:
For the developers out there who are still using CRM 4.0, you can use the following function to generate a custom button, CRM styled, based on the same principles as previous article/function.

// Create Dynamic Button for CRM 4
function CreateButtonCRM4(fieldName, buttonText, buttonWidth, clickEvent)
{
functiontocall=clickEvent;
crmForm.all.item(fieldName + "_c").style.display = "none";

crmForm.all.item(fieldName).DataValue = buttonText;
crmForm.all.item(fieldName).style.borderRight="#3366cc 1px solid";
crmForm.all.item(fieldName).style.paddingRight="5px";
crmForm.all.item(fieldName).style.borderTop="#3366cc 1px solid";
crmForm.all.item(fieldName).style.paddingLeft="5px";
crmForm.all.item(fieldName).style.fontSize="11px";
crmForm.all.item(fieldName).style.backgroundImage="url(/_imgs/btn_rest.gif)";
crmForm.all.item(fieldName).style.borderLeft="#3366cc 1px solid";
crmForm.all.item(fieldName).style.width=buttonWidth;
crmForm.all.item(fieldName).style.cursor="hand";
crmForm.all.item(fieldName).style.lineHeight="18px";
crmForm.all.item(fieldName).style.borderBottom="#3366cc 1px solid";
crmForm.all.item(fieldName).style.backgroundRepeat="repeat-x";
crmForm.all.item(fieldName).style.fontFamily="Tahoma";
crmForm.all.item(fieldName).style.height="20px";
crmForm.all.item(fieldName).style.backgroundColor="#cee7ff";
crmForm.all.item(fieldName).style.textAlign="center";
crmForm.all.item(fieldName).style.overflow="hidden";
crmForm.all.item(fieldName).attachEvent("onmousedown",push_custom_button);
crmForm.all.item(fieldName).attachEvent("onmouseup",release_custom_button);
crmForm.all.item(fieldName).attachEvent("onclick",functiontocall);
crmForm.all.item(fieldName).contentEditable= false;
}


and the output:




Thursday, September 23, 2010

MS CRM 3.0: Set email default font

 Hello again,

 I've been working recently on a way to set the default font within the CRM 3.0 email message edit field. The default font is Tahoma 10, however, a different font was needed (in this code, Arial). From the 3 specified font families, Internet Explorer will use the first one available on the system. As those 3 fonts are rather mundane, it's unlikely they will not be available. Nonetheless, should you decide to use a special font, make sure it's available on each system the code will run on.

 My method uses the "subject" field in order to determine if the form is used to view an email or to edit a new email / a reply email / a forwarded email. It was enough to achieve my goal on this task. The thing about IFrames is that you're not able to determine exactly when they've finished loading. I have attempted to use the onLoad event of the IFrame, however that lead to nothing viable.

 Thus, it came down to the same old workaround of using a timer to make a check against the readyState of the IFrame object.

 The amount of time set on the timers is really up to you - it was enough for my objectives, you might need a quicker / slower time between checks. If the IFrame is not yet loaded, the method sets another timer to make another call attempt later. That, off course, only if the email is in edit mode (the "subject" field is editable).

 Please note that this is not tested on CRM 4.0. I am not aware if the IFrame structure is different than that used in 3.0, therefore I cannot claim it might work on 4.0 as well. ;-)



 Cheers!



Here is the code (in my case, it was placed within the onLoad code of the Email entity):

---------------------
function forceFontFormat(parentNode, fontFamily, fontSizeInPoints, fontSizeInIndex)
{
    if(parentNode)
    {
        try
        {
         var tagName = '';
         if(parentNode.tagName)
         tagName = parentNode.tagName.toLowerCase();
         switch (tagName)
         {
         case 'div':
         case 'p':
         case 'span':
            parentNode.style.fontFamily = fontFamily;
                 parentNode.style.fontSize = fontSizeInPoints + 'pt';
         break;
         case 'font':
         parentNode.setAttribute('face', fontFamily);
         parentNode.setAttribute('size', fontSizeInIndex);
         break;
         }
        }
        catch (err) { }
        if((parentNode.childNodes) && (parentNode.childNodes.length > 0))
        {
            for(var i = 0; i < parentNode.childNodes.length; i++)
            {
                forceFontFormat(parentNode.childNodes[i], fontFamily, fontSizeInPoints, fontSizeInIndex);
            }
        }
    }
}


function forceDefaultCrm30EmailFontFamily()
{
    try
    {
        var isEditable = false;
        try
        {
            var emailSubject = document.getElementById("subject");
            isEditable = emailSubject.isContentEditable;
        }
        catch (secondErr) {}
        if ( isEditable == true)
        {
            var iframe = document.getElementById("descriptionIFrame");
            var forceFont = false;
            try
            {
                if(iframe.contentWindow.document.readyState == "complete")
                    forceFont = true;
            }
            catch (thirdErr)
            {
                forceFont = false;
            }
            if(forceFont == true)
            {
                forceFontFormat(iframe.contentWindow.document.body, 'Arial', '10', '2');
            }
            else
            {
                setTimeout(forceDefaultCrm30EmailFontFamily, 1000);
            }
        }
    }
    catch (firstErr)
    {
        /*alert("CRM Development\n\nThis warning does not affect your work, please ignore it.\nThank you!\n\n\nError message (see below):\n\n" + err.description);*/
    }
}


// Method call
setTimeout(forceDefaultCrm30EmailFontFamily, 1000);

Wednesday, September 15, 2010

Another way of loading certain CRM Views into an IFRAME on the main form

Since every CRM View has its own GUID and can be launched using the Advanced Find out-of-the-box functionality, you can follow several easy steps to load what view you want (with whatever additional filters you want) in a certain IFRAME available on the crmForm.
Here's the scenario: you wanna display your active contacts (My Active Contacts view) in a separate TAB on your account entity form.
- find out the id and objecttypecode of your view;
- create a new TAB and IFRAME on the form of the account entity;
- dynamically set the IFRAME URL as following:
http://[crm_server_name]/[ORGANIZATION_NAME]/AdvancedFind/AdvFind.aspx?EntityCode=[CRM_VIEW_ENTITY_CODE]&QueryId=[CRM_VIEW_ID]&ViewType=1039&AutoRun=True (for our scenario, it would be something like http://CRMSERVER/MyOrganization/AdvancedFind/AdvFind.aspx?EntityCode=2&QueryId={FC3A5B78-1AA4-10C4-1234-12C45B78F01A}&AutoRun=True )
Warning: you must type "AutoRun=True" using this casing. lower/upper case won't trigger the Advanced Find to auto run (and that because the parsing of that parameter is as it is).

There you go - your custom filtered view available anywhere you want on any form :)

Sunday, April 25, 2010

CRM 3.0: Simple button next to a given field

Hello!

The code below generates a simple button next to a given input field (let's say, for instance, the Subject field on a task record). As simple as that.

This is how a standard button is displayed by CRM. The basic magnifying glass on a lookup type field is an image from the standard images CRM comes with (so no, it's not a real button, like those on a Windows Forms application). If you would like that sort of a "button", you'd have to replace the code from the "// Create a new button" line down to the "// Place the button inside the second table TD" line. So, instead of a button INPUT element, you'd create an image field, with onMouseOver and onMouseOut events defined, so it would behave like a "real" button. ;-)

The code and the call:


function attachCRMbutton(currentfieldName)

{
    try
   {
        // Get the parent DIV of the given field
        var parentObject = document.getElementById(currentfieldName).parentNode;
        // Create a holding table
        var myTable = document.createElement("Table");
        // The table should fill the entire surrounding DIV element
        myTable.setAttribute('width', '100%');
        // Add one row to our table
        var myRow = myTable.insertRow(0);
        // Create the TD elements
        var originalChildNodesArea = myRow.insertCell(0);
        var buttonArea = myRow.insertCell(1);
        // For this example, a width of 75 pixels is enough to enclose the "Open address"
        buttonArea.style.width = "75";
        // Place all the original child nodes inside the first table TD
        for(var i = 0; i < parentObject.childNodes.length; i++)
        {
            var myChild = parentObject.childNodes[i];
            originalChildNodesArea.appendChild(myChild);
        }
        // Attach the table to the DIV element
        parentObject.appendChild(myTable);
        // Create a new button
        var myButton = document.createElement('input');
        // Set the open action
        function launchURL()
        {
            window.open('http://crmstuff.blogspot.com');
            return true;
        }
        // Set the CRM-like attributes
        myButton.setAttribute('id', 'linkButton_' + currentfieldName);
        myButton.setAttribute('class', 'txt');
        myButton.setAttribute('type', 'button');
        myButton.setAttribute('maxLength', '50');
        myButton.setAttribute('value', 'Open address');
        myButton.setAttribute('req', '0');
        myButton.attachEvent('onclick', launchURL);
        // Place the button inside the second table TD
        buttonArea.appendChild(myButton);
        // Done
    }
    catch (e) {}
}

// Method call
attachCRMbutton('subject');
 
Good luck and good hunting!

Thursday, December 31, 2009

MS CRM 3.0 "Expected '}'" and "Object expected" errors

Hello, there :-)

Have you ever encountered this situation? You write some decent, valid JS code, throw it inside a CRM field event box, Save & Close x2, publish, test, BAM!-error?

Well, provided your code is actually correct (no logical, typing or access errors), you should check the next thing. In CRM 3.0 at least (not having a 4.0 box around atm., feel free to test if you're kind enough) if you load a piece of code having its last line using a line comment, you're in for trouble. I was lucky to find that out while debugging a whole page and noticed that the line comment I was using was extended to the rest of the CRM JS code (due to CRM placing the CATCH(e){} part of the TRY{} block right on the same line with the last line of my code). That was causing havoc to the entire page.

So, remember this hint: never leave the last line of code having a line comment ( "//" ) or you're in for trouble :D

Cheers!

Monday, October 20, 2008

JavaScript code reuse in CRM

In most of the cases, you don't want to copy-paste your custom methods in your CRM events source code each time you need them.

So, here's an easy approach on javascript code reuse in CRM.

First of all, make sure you have these 2 files: LargeNumber.js and StringsExtended.js located in a custom folder - named CRMStuff - that is also located in the root folder of the Microsoft Dynamics CRM server application (the relative paths to the files should be "/crmstuff/LargeNumbers.js" and "/crmstuff/StringsExtended.js"). As you can see, these 2 files contain custom methods.

Click here to download the source code that allows you to load your *.js files at runtime.

Monday, September 08, 2008

Large Integer division remainder

Recently, I had to obtain the remainder of a (seriously) large integer division (32 digits long divided by another shorter integer; base 10) and found that JavaScript reliably supports operations only on 15-digit long integers. Thus, this what I came up with:

// Gets the remainder from the division operation for LARGE numbers
// Support: positive integers; first parameter must not be 0
function GetRemainder(x, y) {
if ((y != 0) && (x.slice(0, 1) != "-") && (y.slice(0, 1) != "-"))
{
var nr = x;

// Removing the potential first '+' character
if (nr.slice(0, 1) == "+") {nr = nr.slice(1);}
if (y.slice(0, 1) == "+") {y = y.slice(1);}

// Removing leading blank and tab characters on both numbers
while ( (nr.charCodeAt(0) == 32) || (nr.charCodeAt(0) == 9) ){
nr = nr.slice(1);
}
while ( (y.charCodeAt(0) == 32) || (y.charCodeAt(0) == 9) ){
y = y.slice(1);
}

var len = nr.length;

// Checking if any non-digit characters are embedded into the input string
var i = 0;
for (i = 0; i < len; i++)
if (!((nr.charCodeAt(i) >= 48) && (nr.charCodeAt(i) <= 57)) ) {
return -1;
}

var number = parseInt(y,10);
var remainder = 0;
var ignore = 0;
var k = '';

while (ignore < len) {
if (remainder == 0) {
var w1 = y+' ';
var w2 = w1.length-1;
k = nr.slice(ignore, ignore+w2);

ignore += w2;
remainder = parseInt(remainder+k, 10) % number;
} else {
k = nr.slice(ignore, ignore+1);
ignore += 1;
remainder = parseInt(remainder+k, 10) % number;
}
}

return remainder;
}

return -1;
}


Usage:

document.write(GetRemainder("12345678901234567890123456789012", "123"))

will output 27.

Friday, September 05, 2008

OnChange Event

When starting to work with CRM, one of the first things you learn is how to put some script on the onChange event. It's easy to do this and it really works.
Let's say you want to fire that script at the first moment your page is loaded.
In CRM 3.0 you could do that writing a single line :
crmForm.all.yourfield.FireOnChange();
When starting to work with CRM 4.0 I tried to use the same code but it didn't work anymore. I was sooooo disappointed and I hardly found out the solution. That's why i thought of sharing it with you.
The code for firing a script put on the onchange event for CRM 4.0 is:
yourfield_onchange0();

I hope this helps. Happy coding! :)

Random Custom Serial Number Generator

A brief example on how to generate random serial numbers with JavaScript. Enjoy!

// Symbols Array (A-Z, 0-9)
var Symbols = new Array();

// Gets the ascii code for a certain character
function GetAsciiBySymbol(letter)
{
var code = letter.charCodeAt(0);
return code;
}

// Populates a certain array with the A-Z, 0-9 symbols
function PopulateArray(array) {
var Position = 0;

// Letters
for(i=GetAsciiBySymbol('A'); i<=GetAsciiBySymbol('Z'); i++) {

array[Position] = String.fromCharCode(i);
Position++;
}

// Numbers
for(i=GetAsciiBySymbol('0'); i<=GetAsciiBySymbol('9'); i++) {
array[Position] = String.fromCharCode(i);
Position++;
}

}

// Gets the array symbol by a certain index
function GetSymbol(index) {
return Symbols[index];
}

// Generates a new Serial Number
function GenerateSerial(serialLength, separatorSymbol, separatorPositions) {
var serial = "";
var Offset = 0;

for(i=0; i
var rnd = Math.floor(Math.random()*Symbols.length);
serial += GetSymbol(rnd);
}

if(SeparatorPositionsOk(separatorPositions,serialLength)) {
for(i=0; i
var position = separatorPositions[i];
serial = serial.substring(0,position + Offset) + separatorSymbol + serial.substring(position + Offset, serial.length); Offset++;
}
}

return serial;
}

// Checks if a certain array contains only items less than a maximum value
function SeparatorPositionsOk(array, maxValue) {
for(i=0; i maxValue) {
return false;
}
}

return true;
}


// Populate Symbols
PopulateArray(Symbols);

// Example 1 - Format: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
var SepPos = new Array();
SepPos[0] = 5;
SepPos[1] = 10;
SepPos[2] = 15;
SepPos[3] = 20;
var NewSerial = GenerateSerial(25, "-",SepPos);
alert("Serial Number: " + NewSerial);


// Example 2 - Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
SepPos = new Array();
SepPos[0] = 8;
SepPos[1] = 12;
SepPos[2] = 16;
SepPos[3] = 20;
SepPos[4] = 24;
NewSerial = GenerateSerial(32, "-",SepPos);
alert("Serial Number: " + NewSerial);

// Example 3 - Format: XXX-XXXXXXX
SepPos = new Array();
SepPos[0] = 3;
NewSerial = GenerateSerial(10, "-",SepPos);
alert("Serial Number: " + NewSerial);