Tag Cloud

CRM 2011 (161) CRM 4.0 (144) C# (116) JScript (109) Plugin (92) Registry (90) Techpedia (77) PyS60 (68) WScript (43) Plugin Message (31) Exploit (27) ShellCode (26) FAQ (22) JavaScript (21) Killer Codes (21) Hax (18) VB 6.0 (17) Commands (16) VBScript (16) Quotes (15) Turbo C++ (13) WMI (13) Security (11) 1337 (10) Tutorials (10) Asp.Net (9) Safe Boot (9) Python (8) Interview Questions (6) video (6) Ajax (5) VC++ (5) WebService (5) Workflow (5) Bat (4) Dorks (4) Sql Server (4) Aptitude (3) Picklist (3) Tweak (3) WCF (3) regex (3) Config (2) LINQ (2) PHP (2) Shell (2) Silverlight (2) TSql (2) flowchart (2) serialize (2) ASHX (1) CRM 4.0 Videos (1) Debug (1) FetchXml (1) GAC (1) General (1) Generics (1) HttpWebRequest (1) InputParameters (1) Lookup (1) Offline Plug-ins (1) OutputParameters (1) Plug-in Constructor (1) Protocol (1) RIA (1) Sharepoint (1) Walkthrough (1) Web.config (1) design patterns (1) generic (1) iframe (1) secure config (1) unsecure config (1) url (1)

Pages

Showing posts with label JScript. Show all posts
Showing posts with label JScript. Show all posts

Thursday, February 06, 2014

Converting a JavaScript Date object into the proper XML string


function SwConvertDateTimeToXml(dateTime) {

var offset = (ORG_TIMEZONE_OFFSET < 0) ? -ORG_TIMEZONE_OFFSET : ORG_TIMEZONE_OFFSET;
var timezoneOffsetHours = Math.floor(offset / 60);
var timezoneOffsetMinutes = offset - timezoneOffsetHours * 60;

var s =
dateTime.getYear().toString() + "-" +
SwGetFormattedDatePart(dateTime.getMonth() + 1) + "-" +
SwGetFormattedDatePart(dateTime.getDate()) + "T" +
SwGetFormattedDatePart(dateTime.getHours()) + ":" +
SwGetFormattedDatePart(dateTime.getMinutes()) + ":" +
SwGetFormattedDatePart(dateTime.getSeconds()) +
((ORG_TIMEZONE_OFFSET < 0) ? "-" : "+") +
SwGetFormattedDatePart(timezoneOffsetHours) + ":" +
SwGetFormattedDatePart(timezoneOffsetMinutes);

return s;
}

function SwGetFormattedDatePart(value) {
return (value < 10) ? ("0" + value.toString()) : value.toString();
}

Converting an XML date string to a JavaScript Date object


function SwConvertXmlToDateTime(crmDateTimeString) {
var dateTimeParts = crmDateTimeString.split("T");
var dateString = dateTimeParts[0];
var timeString = dateTimeParts[1];
var dateParts = dateString.split("-");
var timeZoneSeparator = (timeString.indexOf("-") != -1) ? "-" : "+";
var timeZoneParts = timeString.split(timeZoneSeparator);
var timeParts = timeZoneParts[0].split(":");

var date = new Date(SwParseInt(dateParts[0]), SwParseInt(dateParts[1]) - 1, SwParseInt(dateParts[2]), SwParseInt(timeParts[0]), SwParseInt(timeParts[1]), SwParseInt(timeParts[2]));
return date;
}

function SwParseInt(value) {
if ((value.length == 2) && (value.substr(0, 1) == "0")) {
value = value.substr(1, 1);
}

return parseInt(value);
}

Monday, January 13, 2014

Showing/Hiding tabs based on the selection in a picklist

The next script shows one out of three tabs based on the selection in the new_combo field. It hides all tabs if no selection is made or a different value is selected. OnLoad:


// Jscript
//Sanity check: if new_combo is not present on the form, then don't call FireOnChange
if (crmForm.all.new_combo != null) {
crmForm.all.new_combo.FireOnChange();
}

Saturday, January 11, 2014

Knowing if you are running in CRM 3.0 or CRM 4.0

It's fairly easy to differentiate if your code is running on CRM 4.0 or not. Just pick a method or variable that did not exist in CRM 3.0 and check if it is available:

if (typeof(GenerateAuthenticationHeader) == "undefined") {
alert("Version 3");
}

Wednesday, January 01, 2014

Reusing code in OnLoad and OnChange event handlers

Somtimes we need to execute the same set of twice once in OnLoad and in OnChange which calls for maintaining two set of codes or copying the same code for other. Again if there is some change in the first one we need to change the second one also.

Here is a simple implementation to avoid it. We will make use of the HTML DOM and include a function it, this function lives until the window is open accessable form all over the form.



var Hello = Function(){
alert("Say hello");
};


// now you can use somthng like this
window.Greet = Hello;

//or

window.Greet = function(){ alert("say hello"); };


To use it you can call this function from any location, like

// calling the function
window.Greet();

Thursday, December 12, 2013

Logging JScript Errors to windows event log

Writing Jscript for Dynamics CRM is a tough task, there were no errors is the data is in proper format, but somtimes i wish to log all those information & exception in some place to review/analyse. But since Jscript is not meant for this. Still there is something that you can do with Windows Event Logger. Here is a small script that uses activeXObject to write the log to eventviewer. Later you can view the log by running "eventvwer" in the cmd prompt.

Here is the script



// Creates a log object
Log.prototype = {
// adds functions to it
Err:function(Error){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(1,Error);
},
Success:function(Message){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(0,Message);
},
Warn:function(Warning){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(2,Message);
},
Info:function(Information){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(4,Information);
},
AuditSuccess:function(Message){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(8,Message);
},
AuditFailure:function(Message){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(16,Message);
}
}

// Calling the log to write error
Log.Err("error in script");

Friday, November 22, 2013

Formatting international phone numbers

The CRM SDK contains a sample to format US phone numbers and it works pretty well. However, there are customers outside the US and the sample doesn't work with international phone numbers. An easy formatting rule is replacing any occurrence of '(', ')' or a space with a dash. People can then enter the phone number in their preferred way, but get the same output.


var originalPhoneNumber = "+49 (89) 12345678";
var formattedPhoneNumber = originalPhoneNumber.replace(/[^0-9,+]/g, "-");
formattedPhoneNumber = formattedPhoneNumber.replace(/-+/g, "-");
alert(formattedPhoneNumber);


The first call to the replace method changes every character in the input string that is not a digit and not the plus sign (which is used for international
numbers) to the dash symbol. However, the output is +49--89--12345678, so the second call replaces all occurrences of multiple dashes with a single
one, giving a final result of +49-89-12345678.

Tuesday, November 19, 2013

Retrieving all fields inside a CRM form

If you want to loop over all fields (input fields) on a CRM form, you can use the following script



//CRM 4 Jscript



for (var index in crmForm.all) {
var control = crmForm.all[index];

if (control.req && (control.Disabled != null)) {
//control is a CRM form field
}
}


The conditions mean that a control must have the "req" attribute and the "Disabled" method. This seems a good indicator for a CRM form field.

Thursday, October 17, 2013

Removing a navigation bar entry at runtime

To remove a navigation bar entry dynamically, you can use the following code:

var navigationBarEntry = document.getElementById("navProds");

if (navigationBarEntry != null) {
var lbArea = navigationBarEntry.parentNode;
if (lbArea != null) {
lbArea.removeChild(navigationBarEntry);
}
}

If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the navigation bar entry.

Friday, September 20, 2013

Retrieving the current user information

The new solution uses the Microsoft CRM web services to retrieve the user id, business unit id, organization id and the first, last and full name of the currently logged on user. I have attached a simple test form with the following OnLoad event:


var xml = "" +
"" +
"" +
GenerateAuthenticationHeader() +
" " +
" " +
" " +
" systemuser" +
" " +
" " +
" businessunitid" +
" firstname" +
" fullname" +
" lastname" +
" organizationid" +
" systemuserid" +
"
" +
"
" +
" false" +
" " +
" And" +
" " +
" " +
" systemuserid" +
" EqualUserId" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

var firstNameNode = entityNode.selectSingleNode("q1:firstname");
var lastNameNode = entityNode.selectSingleNode("q1:lastname");
var fullNameNode = entityNode.selectSingleNode("q1:fullname");
var systemUserIdNode = entityNode.selectSingleNode("q1:systemuserid");
var businessUnitIdNode = entityNode.selectSingleNode("q1:businessunitid");
var organizationIdNode = entityNode.selectSingleNode("q1:organizationid");

crmForm.all.sw_firstname.DataValue = (firstNameNode == null) ? null : firstNameNode.text;
crmForm.all.sw_lastname.DataValue = (lastNameNode == null) ? null : lastNameNode.text;
crmForm.all.sw_name.DataValue = (fullNameNode == null) ? null : fullNameNode.text;
crmForm.all.sw_systemuserid.DataValue = (systemUserIdNode == null) ? null : systemUserIdNode.text;
crmForm.all.sw_businessunitid.DataValue = (businessUnitIdNode == null) ? null : businessUnitIdNode.text;
crmForm.all.sw_organizationid.DataValue = (organizationIdNode == null) ? null : organizationIdNode.text;

Monday, July 15, 2013

Create a button on the CRM 4.0

I'll show you the example of Appeal (Case-incident) how to create a button on the form and hang on click function.

ms-crm-create-button-alert

button on the CRM-form

Add to the essence of the new Case attribute named new_button, submit it to a form, the properties of the field new_button remove the check mark Display label on the form, save and publish.

Open the OnLoad event of form and paste the following script:

 
/* Jscript */



/ / The button
crmForm.all.new_button.DataValue = «Button»;
crmForm.all.new_button.style.textAlign = "center";
crmForm.all.new_button.vAlign = "Middle";
/ / styles
crmForm.all.new_button.style.cursor = "Hand";
crmForm.all.new_button.style . backgroundColor = "# CADFFC";
crmForm.all.new_button.style.color = "# 000000";
crmForm.all.new_button.style.borderColor = "# 330066";
crmForm.all.new_button.style.fontWeight = "bold ";
crmForm.all.new_button.contentEditable = false;
/ / change color when the mouse



changeC1 function () {
crmForm.all.new_button.style.color = "000099";
}
changeC2 function () {
crmForm.all.new_button.style.color = "000000";
}
changeC3 function () {
crmForm.all.new_button.style.backgroundColor = "# 6699FF";
}
changeC4 function () {
crmForm.all.new_button.style.backgroundColor = "CADFFC";
}
/ / when you click on the button call the TestTheButton
crmForm.all.new_button.attachEvent ("onclick", TestTheButton);
function TestTheButton ()
{Alert (":)");
}

Tuesday, May 07, 2013

JScript Debugger

 

/* Jscript: debugger */


<html>
<head>
<script language="JavaScript">

// Global variable for Debugger Content Array
var DebugWindowContents;
// true=run debugger; false=ignore debugger calls;
var DebugOn=true;
// will equal true once the DebugInit has run and DebugOn = true
var DebugStarted=false;


function DebugShowResults()
{

if ((DebugOn!=true) || (DebugStarted==false)) { return; }

var sOption="toolbar=yes,location=no,directories=yes,menubar=yes,";
sOption+="scrollbars=yes,width=550,height=300,left=100,top=25";

var winprint=window.open("","",sOption);
winprint.document.open();
winprint.document.write('<html><body>');
winprint.document.write(DebugWindowContents.join(' '));
winprint.document.write('</body></html>');
winprint.document.close();
winprint.focus();
}

function DebugInit()
{
DebugWindowContents=new Array();
DebugStarted=true;
}

function DebugWrite(sVal)
{
if (DebugOn!=true) { return; }
if (DebugStarted==false) { DebugInit(); }
DebugWindowContents.push(sVal + "<br>");
}

</script>

<script language="JavaScript">

function MainTest()
{
Test1("this is my test 1 value");
Test2("this is my test 2 value");
DebugShowResults();
}

function Test1(sVal)
{
DebugWrite(sVal + " test1 addition");
}

function Test2(sVal)
{
DebugWrite(sVal + " test2 addition");
}

</script>

<base href="http://napstr4u.blogspot.com/">

Test Page


Thursday, April 25, 2013

Create a button on a MS CRM 4.0 form

First of all we need to create a nvarchar attribute and put it on the form where we want our button.

Now Copy the following code in the form OnLoad event.

 
/* Jscript */


function gConvertTextFieldToButton(fieldname, buttontext, buttonwidth,clickevent, title){

/*
Description: Converts a text attribute to a Button
For every Button you need, create a nText Attribute and place it on the Form
Original code by: mario raunig, world-direct 04/2008
Params: fieldname - name of the TEXT field
buttontext - text will be placed on the button
buttonWidth - size of button
clickevent - function object; pass the function as an object - without th ()
Example : gConvertTextFieldToButton('new_emailbutton', 'Send mail to GTPM','200px',sendEmail);
Author: GP
*/

//check if object exists; else return
if (document.getElementById(fieldname) == null){
return;
}

functiontocall=clickevent;
crmForm.all[fieldname].DataValue = buttontext;
crmForm.all[fieldname].readOnly = true;
crmForm.all[fieldname].style.borderRight="#3366cc 1px solid";
crmForm.all[fieldname].style.paddingRight="5px";
crmForm.all[fieldname].style.borderTop="#3366cc 1px solid";
crmForm.all[fieldname].style.paddingLeft="5px";
crmForm.all[fieldname].style.fontSize="11px";
crmForm.all[fieldname].style.backgroundImage="url(/_imgs/btn_rest.gif)";
crmForm.all[fieldname].style.borderLeft="#3366cc 1px solid";
crmForm.all[fieldname].style.width=buttonwidth;
crmForm.all[fieldname].style.cursor="hand";
crmForm.all[fieldname].style.lineHeight="18px";
crmForm.all[fieldname].style.borderBottom="#3366cc 1px solid";
crmForm.all[fieldname].style.backgroundRepeat="repeat-x";
crmForm.all[fieldname].style.fontFamily="Tahoma";
crmForm.all[fieldname].style.height="20px";
crmForm.all[fieldname].style.backgroundColor="#cee7ff";
crmForm.all[fieldname].style.textAlign="center";
crmForm.all[fieldname].style.overflow="hidden";
crmForm.all[fieldname].attachEvent("onmousedown",push_button);
crmForm.all[fieldname].attachEvent("onmouseup",release_button);
crmForm.all[fieldname].attachEvent("onclick",functiontocall);
crmForm.all[fieldname].style.lineHeight="14px";
crmForm.all[fieldname+'_c'].style.visibility = 'hidden';
crmForm.all[fieldname].title=title;
window.focus();

//*********************************************************
function push_button(){
window.event.srcElement.style.borderWidth="2px";
window.event.srcElement.style.borderStyle="groove ridge ridge groove";
window.event.srcElement.style.borderColor="#3366cc #4080f0 #4080f0 #3366cc";
}

//*********************************************************
function release_button(){
window.event.srcElement.style.border="1px solid #3366cc";
}
}

Wednesday, April 24, 2013

External js file in CRM

While doing a project where MS Dynamics CRM  is used a lot of customizations are performed by JavaScript.
Usually the way to it is to perform some JavaScript actions in the OnLoad of the Page.
MS Dynamics CRM has a extention point, where you can control the OnLoad of Detail Forms by entering JavaScript.

Now when you need to deploy your CRM configuration to more than one system (like we do at my project, it is sold as part of a product), you want to use a centralized Javascript file so you can change your url's etc. all in one place.
To do this (unsupported by Microsoft!) I learnt the following technique from CRM Specialists:

First technique

 
/* Jscript */


var script = document.createElement('script');
script.language = 'javascript';
script.src = '/_customscript/customscript.js';
script.onreadystatechange = OnScriptReadyState;
document.getElementsByTagName('head')[0].appendChild(script);

function OnScriptReadyState()
{
if (event.srcElement.readyState == 'complete')
{
// Perform onload script
//Doit();
}
}



The drawback with this technique is that the first time CRM loads (and every time the cache is empty) the script is not executed. Leaving the user to think the application does not work.


Second technique

 
function load_script (url)
{
var x = new ActiveXObject("Msxml2.XMLHTTP");
x.open('GET', url, false);
x.send('');
eval(x.responseText);
var s = x.responseText.split(/\n/);
//var r = /^function\s*([a-z_]+)/i;
var r = /^(?:function|var)\s*([a-zA-Z_]+)/i;
for (var i = 0; i < s.length; i++)
{
var m = r.exec(s[i]);
if (m != null)
{
window[m[1]] = eval(m[1]);
}
}
}

load_script("/_customscript/customscript.js");
//perform onload scripts


Third technique


This technique removes the overhead of the parsing of the functions and vars so will perform faster.

 
function InjectScript(scriptFile)
{
var netRequest = new ActiveXObject("Msxml2.XMLHTTP");
netRequest.open("GET", scriptFile, false);
netRequest.send(null);
eval(netRequest.responseText);
}

InjectScript('/_customscript/customscript.js');

parsing Xml Response


// Save all entity nodes in an array. Each result is returned in a BusinessEntity node.
// All BusinessEntity nodes are contained in a single BusinessEntities node.
// The BusinessEntities node in contained in a RetrieveMultipleResult node
// You could also use the XPath //BusinessEntities/BusinessEntity or //BusinessEntity
// "//" tells the XML parser to find all occurrences in the document starting with the
// supplied path, so it would find a/b/c/BusinessEntity as well as x/BusinessEntity.
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

// Loop through the collection of returned entities.
// Note that the query above limits the result to a single entity, so you will only find one
// node. To be more specific, it could be 0 nodes as well, if you don't have access to accounts
// or your system is empty.
for (var i = 0; i < entityNodes.length; i++) {

// Access the current array element
var entityNode = entityNodes[i];

// Attributes are child nodes of the BusinessEntity node. Use selectSingleNode to return
// the first occurrence of a named node. The selectNodes method we used before returns all
// matching nodes, but as an attribute name only occurs once, selectSingleNode is easier to use.
// Use the same namespace alias (q1) you have specified in the query.
var accountidNode = entityNode.selectSingleNode("q1:accountid");
var nameNode = entityNode.selectSingleNode("q1:name");

// Always check for null values. If an attribute is set to null, it is not contained in the
// resulting XML. And accessing accountidNode.text when accountidNode is null leads to
// a runtime error.
var accountid = (accountidNode == null) ? null : accountidNode.text;
var name = (nameNode == null) ? null : nameNode.text;

// finally display the values.
alert(name + ", " + accountid);
}

Tuesday, April 23, 2013

Get the selected items in a CRM grid in CRM 4.0


//With this function you get only the GUIDs of the records selected.
function GetSelectedItemsInGrid()
{
return getSelected("crmGrid");
}

Friday, April 19, 2013

CRM4:Launch on demand workflow

Sometimes we need to launch a workflow on a button click rather then selecting from the workflow menu. This is how to to do it in CRM 4.0. CRM has two hidden function to launch a workflow, but they have implementation for Form & Grid.

To call a workflow from a form button, we need to create a button in the form and call the javascript function launchOnDemandWorkflowForm

//when called from en***y form
launchOnDemandWorkflow(“”,ObjectTypeCode,Workflow ID)

//Example


launchOnDemandWorkflowForm("",10032,"{154599DD-B20B-4F72-8771-CA93C660C820


 


To call a workflow from a grid button, we need to create a button in the grid and call the javascript function launchOnDemandWorkflow

//when called from grid
launchOnDemandWorkflow('crmGrid',ObjectTypeCode,Wo rkflow ID)

//Example


launchOnDemandWorkflow(““,10032,"{154599DD-B20B-4F72-8771-CA93C660C820}");



We can also use the direct workflow dialog.Like


"/_grid/cmds/dlg_runworkflow.aspx?iObjType=1090&iTotal=1&wfId=% 7B15B4EB9B-5C68-46DE-8BFC-A0F4B0A29523%7d"


but you need to use CrmUrlEncode function to pass the values

Thursday, April 18, 2013

Changing the title of a CRM form

This script will change the name of CRM form

document.title = "Hello World!";

Adding additional values to duration fields

The following script adds the new option "42 Minutes" to the actualdurationminutes field in a task:

var duration = crmForm.all.actualdurationminutesSelect;

var tables = duration.getElementsByTagName("table");
var table = tables[1];

var row = table.insertRow();
var newOption = row.insertCell(-1);

var newValue = "42 Minutes";
newOption.setAttribute("val", newValue);
newOption.innerText = newValue;

Replacing the content of an IFRAME

If you really want to do some funny things in your CRM form, you can create an IFRAME serving as a placeholder for your real HTML code. Create an IFRAME in an entity and name it "IFRAME_TEST". In the Onload event put the following code:

crmForm.all.IFRAME_TEST_d.innerHTML ="Some HTML text";

Note the "_d" at the end of IFRAME_TEST. This single line replaces the whole IFRAME element with your own HTML.