to UTC/JSON Date

 

// to UTC/JSON Date
Number.prototype.addZero = function () { return (this < 10) ? "0" +
this : this; };
var convertDate = function (d) {
var d, s, u, uh, um, us;
//d = new Date();
s = d.getFullYear() + "-";
s += (d.getMonth() + 1).addZero() + "-"; //getMonth returns an
integer in the range 0-11
s += d.getDate().addZero() + "T";
s += d.getHours().addZero() + ":";
s += d.getMinutes().addZero() + ":";
s += d.getSeconds().addZero();
u = 0 - d.getTimezoneOffset(); //getTimezoneOffset will
be positive if you are behind UTC, and negative if you are ahead of
UTC.
us = (u >= 0) ? "+" : "-";
u = Math.abs(u);
uh = Math.floor(u / 60).addZero();
um = (u % 60).addZero();
s += us;
s += uh + ":";
s += um;
alert(s);
return (s);
};

// call
convertDate(new Date());

Parse XmlHttp Response

// Parse XmlHttp Response
function parseResponse(responseXML, attributename) {

    debugger;
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML(responseXML);
    x = xmlDoc.getElementsByTagName("a:KeyValuePairOfstringanyType");
    for (i = 0; i < x.length; i++) {
        if (x[i].childNodes[0].text == attributename) {
            //we decode the base 64 contents and alert the HTML of the Iframe
            alert(x[i].childNodes[1].text);
        }

    }
}

XmlHttp Request

// XmlHttp Request
var AjaxRequest = function (crmSvcUrl, soapString) {
var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
XmlHttp.open("POST", crmSvcUrl, false);
XmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XmlHttp.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
XmlHttp.setRequestHeader("Content-Length", soapString.length);
XmlHttp.send(soapString);
var resultXml = XmlHttp.responseXML;
return resultXml;
};

Create SOAP Envelop

// Create SOAP Envelop
var createSOAP = function (fxml) {
var soap2 = "";
soap2 += GenerateAuthenticationHeader();
soap2 += "";
soap2 += "";
soap2 += "";
soap2 += fxml;
soap2 += "";
soap2 += "";
soap2 += "";
soap2 += "";
return soap2;
};

return if day is weekday

// return if day is weekday
var Weekday = function (chkDt) {
if (chkDt.getDay() > 0 && chkDt.getDay() < 6) {
//"Sorry, it's a weekday.";
return true;
}
else {
//"Hooray, it's a weekend!";
return false;
}
}; //Ef

JSON date fromat to date Object

<pre class="brush: c#">
//JSON date fromat to date Object
var jsondtobj = function (txt) {
var year, month, day;
var filler = '.*?'; // Non-greedy match on filler
var yre2 = '((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])';
// Year 1
var yp = new RegExp(filler + yre2, ["i"]);
var ym = yp.exec(txt);
if (ym != null) {
var year1 = ym[1];
year = year1.replace(/</, "&lt;");
}


var mre2 = '(?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))(?![\\d])'; //
Uninteresting: day
var mre4 = '((?:(?:[0-2]?\\d{1})|(?:[3][01]{1})))(?![\\d])'; // Month 1

var mp = new RegExp(filler + mre2 + filler + mre4, ["i"]);
var mm = mp.exec(txt);
if (mm != null) {
var mon1 = mm[1];
month = mon1.replace(/</, "&lt;") - 1;
}


var dre2 = '(?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))(?![\\d])'; //
Uninteresting: day
var dre4 = '(?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))(?![\\d])'; //
Uninteresting: day
var dre6 = '((?:(?:[0-2]?\\d{1})|(?:[3][01]{1})))(?![\\d])'; // Day 1

var dp = new RegExp(filler + dre2 + filler + dre4 + filler + dre6, ["i"]);
var dm = dp.exec(txt);
if (dm != null) {
var day1 = dm[1];
day = day1.replace(/</, "&lt;");
}
var dateObject = new Date(); dateObject.setDate(day);
dateObject.setMonth(month); dateObject.setYear(year);
return dateObject;
}; //
</pre>

Extend Date Object with new function using Namespace

// Extend Date Object with new function using Namespace
//Date.prototype.daysBetween
Date.prototype.daysBetween = function (date1, date2) {
    //Get 1 day in milliseconds
    var one_day = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = date2_ms - date1_ms;
    //take out milliseconds
    difference_ms = difference_ms / 1000;
    var seconds = Math.floor(difference_ms % 60);
    difference_ms = difference_ms / 60;
    var minutes = Math.floor(difference_ms % 60);
    difference_ms = difference_ms / 60;
    var hours = Math.floor(difference_ms % 24);
    var days = Math.floor(difference_ms / 24);

    return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
};

Create new Queue using Early Bound

// ** Create new Queue ** using Early Bound

//Create new queues and store their returned GUIDs in variables for later use.

Queue sourceQueue = new Queue

{

    Name = "Example Queue 1",

    Description = "This is an example queue.",

};

 

Guid _QueueId = _service.Create(sourceQueue);

Console.WriteLine("Created {0}", sourceQueue.Name);

DeleteOptionSetRequest

// ** DeleteOptionSetRequest **

// deletes global option set

DeleteOptionSetRequest deleteRequest = new DeleteOptionSetRequest

{

    Name = "_globalOptionSetName"

};

 

_service.Execute(deleteRequest);

 

DeleteEntityRequest

// ** DeleteEntityRequest **

// Deletes entity with logical name

DeleteEntityRequest request = new DeleteEntityRequest()

{

    LogicalName = "_customEntityName",

};

_service.Execute(request);

DeleteAttributeRequest

// ** DeleteAttributeRequest **

// Delete attribute present in entity.

 

// Create the request object

DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest

{

    // Set the request properties 

    EntityLogicalName = "EntityLogicalName",

    LogicalName = "anAttribute_SchemaName"

};

// Execute the request

_service.Execute(deleteAttribute);

 

create global option set

// ** create global option set **

// Define the request object and pass to the service.

CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest

{

    // Create a global option set (OptionSetMetadata).

    OptionSet = new OptionSetMetadata

    {

        Name = "_globalOptionSetName",

        DisplayName = new Label("Example Option Set", 1033),

        IsGlobal = true,

        OptionSetType = OptionSetType.Picklist,

        Options = 

    {

        new OptionMetadata(new Label("Open", 1033), null),

        new OptionMetadata(new Label("Suspended", 1033), null),

        new OptionMetadata(new Label("Cancelled", 1033), null),

        new OptionMetadata(new Label("Closed", 1033), null)

    }

    }

};

 

// Execute the request.

CreateOptionSetResponse optionsResp =

    (CreateOptionSetResponse)_service.Execute(createOptionSetRequest);

CRM 4.0 Form JScript

// CRM 4.0 Form Scripts Example
//Set Field Value
crmForm.all.crmfieldscemaname.DataValue= "value";

//Get Field Value
var value = crmForm.all.crmfieldscemaname.DataValue;

//Set Requirement Field
crmForm.all.crmfieldscemaname.setAttribute( "req",0);
//or
crmForm.all.crmfieldscemaname_c.classname= "n";

// Set Recommended
crmForm.all.crmfieldscemaname.setAttribute( "req",1);
//or
crmForm.all.crmfieldscemaname_c.className= "rec";

//Set Required
crmForm.all.crmfieldscemaname.setAttribute( "req",2);
//or
crmForm.all.crmfieldscemaname_c.className= "req";

//Disable a field
crmForm.all.crmfieldscemaname.Disabled= true;

//Enable a Field
crmForm.all.crmfieldscemaname.Disabled= false;

//hide a field
crmForm.all.crmfieldscemaname.style.Display= "none";
//or
crmForm.all.crmfieldscemaname_c.style.Display= "none";

//Show a field
crmForm.all.crmfieldscemaname.style.Display= "block";
//or
crmForm.all.crmfieldscemaname_c.style.Display= "inline";

//Set PickList Value
crmForm.all.crmfieldscemaname.DataValue= "none";

//Get PickList Value
var value=crmForm.all.crmfieldscemaname.DataValue;

Hide Tab using JScript

//CRM 4.0
crmForm.all.tabIndexTab.style.visibility = "hidden";

// CRM 2011
Xrm.Page.ui.tabs.get(TabIndex).setVisible(false);
Xrm.Page.ui.tabs.get(TabIndex).setVisible(true);
//Or
Xrm.Page.ui.tabs.get(TabName).setVisible(false);

CreateOneToManyRequest

// ** CreateOneToManyRequest **

// creates an entity relationship between Account and Campaign entities by using CreateOneToManyRequest

CreateOneToManyRequest createOneToManyRelationshipRequest =

        new CreateOneToManyRequest

        {

            OneToManyRelationship =

            new OneToManyRelationshipMetadata

            {

                ReferencedEntity = "account",

                ReferencingEntity = "campaign",

                SchemaName = "new_account_campaign",

                AssociatedMenuConfiguration = new AssociatedMenuConfiguration

                {

                    Behavior = AssociatedMenuBehavior.UseLabel,

                    Group = AssociatedMenuGroup.Details,

                    Label = new Label("Account", 1033),

                    Order = 10000

                },

                CascadeConfiguration = new CascadeConfiguration

                {

                    Assign = CascadeType.Cascade,

                    Delete = CascadeType.Cascade,

                    Merge = CascadeType.Cascade,

                    Reparent = CascadeType.Cascade,

                    Share = CascadeType.Cascade,

                    Unshare = CascadeType.Cascade

                }

            },

            Lookup = new LookupAttributeMetadata

            {

                SchemaName = "new_parent_accountid",

                DisplayName = new Label("Account Lookup", 1033),

                RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                Description = new Label("Sample Lookup", 1033)

            }

        };

 

 

CreateOneToManyResponse createOneToManyRelationshipResponse =

    (CreateOneToManyResponse)_service.Execute(createOneToManyRelationshipRequest);

 

Create a string attribute


// ** Create a string attribute **

StringAttributeMetadata stringAttribute = new StringAttributeMetadata

{

    // Set base properties

    SchemaName = "new_string",

    DisplayName = new Label("Sample String", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("String Attribute", 1033),

    // Set extended properties

    MaxLength = 100

};

 

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = stringAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

Create a picklist attribute (Option set)


// ** Create a picklist attribute (Option set) **

PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata

{

    // Set base properties

    SchemaName = "new_picklist",

    DisplayName = new Label("Sample Picklist", _languageCode),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Picklist Attribute", _languageCode),

    // Set extended properties

    // Build local picklist options

    OptionSet = new OptionSetMetadata

    {

        IsGlobal = false,

        OptionSetType = OptionSetType.Picklist,

        Options = 

        {

        new OptionMetadata(

            new Label("Created", _languageCode), null),

        new OptionMetadata(

            new Label("Updated", _languageCode), null),

        new OptionMetadata(

            new Label("Deleted", _languageCode), null)

        }

    }

};

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = pickListAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

Hide Section in Tab on CRM 4.0 form

crmForm.all..parentElement.parentElement.parentElement.style.display="none";
//Another way from top down:
document.getElementById("tab").childNodes[0].rows[].style.display = "none";
//  is zero based tab number from left.  is zero based section number from top.
//To show it back, simply replace "none" with "block".

Hide Tab on CRM 4.0 form

document.getElementById("tabTab").style.display = "none"; //  zero based tab number from left

Hide Field / Attribute on CRM 4.0 form

<


pre class="brush: csharp">
crmForm.all.


<fieldname>_c.style.display = "none";
crmForm.all.


<fieldname>_d.style.display = "none";
</


pre>

Create a integer attribute


// ** Create a integer attribute **   

IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata

{

    // Set base properties

    SchemaName = "new_integer",

    DisplayName = new Label("Sample Integer", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Integer Attribute", 1033),

    // Set extended properties

    Format = IntegerFormat.None,

    MaxValue = 100,

    MinValue = 0

};

 

 

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = integerAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

 

ModifyAccess Message

Remarks

To use this message, pass an instance of the ModifyAccessRequest class as the request parameter in the Execute method.

This action applies to all child instances of the target entity instance. For all child instances, if the caller does not have share privileges for those entity types, or share rights to the instances, the child instances are not shared. As a result, the owner of the entity instance, or a user who shares the instance with share rights, automatically has share rights to all child instances of the target entity instance. In this case, only the lack of privileges to a particular entity type prevents the child instances from being shared.

For a description of how actions on a parent instance affect child instances, see Cascading Rules.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see ModifyAccess Privileges.

    
//# The following code example shows how to use the ModifyAccess message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the Security Principal Object
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.User;

// PrincipalId is the Guid of the user whose access is being modified
principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

// Create the PrincipalAccess
PrincipalAccess principalAccess = new PrincipalAccess();

// Set the PrincipalAccess Object's Properties
principalAccess.Principal = principal;

// gives the principal access to read
principalAccess.AccessMask = AccessRights.ReadAccess;

// Create the Target Object for the Request
TargetOwnedAccount target = new TargetOwnedAccount();

// EntityId is the Guid of the account whose access is being modified
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the Request Object
ModifyAccessRequest modify = new ModifyAccessRequest();

// Set the Request Object's Properties
modify.PrincipalAccess = principalAccess;
modify.Target = target;

// Execute the Request
ModifyAccessResponse modified = (ModifyAccessResponse)service.Execute(modify);

Create a decimal attribute

// ** Create a decimal attribute **   

DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata

{

    // Set base properties

    SchemaName = "new_decimal",

    DisplayName = new Label("Sample Decimal", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Decimal Attribute", 1033),

    // Set extended properties

    MaxValue = 100,

    MinValue = 0,

    Precision = 1

};

 

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = decimalAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

 

Create a date time attribute

// ** Create a date time attribute **

DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata

{

    // Set base properties

    SchemaName = "new_datetime",

    DisplayName = new Label("Sample DateTime", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("DateTime Attribute", 1033),

    // Set extended properties

    Format = DateTimeFormat.DateOnly,

    ImeMode = ImeMode.Disabled

};

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = dtAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

Create a boolean attribute

// ** Create a boolean attribute **

// Boolean attribute

BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata

{

    // Set base properties

    SchemaName = "new_boolean",

    DisplayName = new Label("Sample Boolean", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Boolean Attribute", 1033),

    // Set extended properties

    OptionSet = new BooleanOptionSetMetadata(

        new OptionMetadata(new Label("True", 1033), 1),

        new OptionMetadata(new Label("False", 1033), 0)

        )

};

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = boolAttribute

};

 

// Execute the request.

_service.Execute(createAttributeRequest);

 

Create a money attribute

// ** Create a money attribute **

MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata

{

    // Set base properties

    SchemaName = "new_money",

    DisplayName = new Label("Money Picklist", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Money Attribue", 1033),

    // Set extended properties

    MaxValue = 1000.00,

    MinValue = 0.00,

    Precision = 1,

    PrecisionSource = 1,

    ImeMode = ImeMode.Disabled

};

 

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = moneyAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

 

CanManyTomanyRequest

// ** CanManyTomanyRequest **

// Determines whether the entity can participate in a many-to-many relationship.

CanManyToManyRequest canManyToManyRequest = new CanManyToManyRequest

{

    EntityName = "entity_logicalname"

};

 

CanManyToManyResponse canManyToManyResponse =

    (CanManyToManyResponse)_service.Execute(canManyToManyRequest);

 

if (!canManyToManyResponse.CanManyToMany)

{

    Console.WriteLine(

        "Entity {0} can't participate in a many-to-many relationship.", 

        "entity_logicalname");

}

GetProcessInfo using WMI

Sub GetProcess()
  Set objWMI = GetObject("winmgmts:")
  Set instanzen = objWMI.InstancesOf("Win32_Process")
  'MakeTabH "Instance","CommandLine"
  For Each objInstance In instanzen
    'MakeTabD objInstance.Name , objInstance.CommandLine
  write objInstance.Name  & " : " & objInstance.CommandLine & ""
  'document.frames.myiframe.document.body.style.font="arial"
  Next
End Sub

DeleteOptionValueRequest

// ** DeleteOptionValueRequest **

// to remove the newly inserted label.

DeleteOptionValueRequest deleteOptionValueRequest =

    new DeleteOptionValueRequest

    {

        OptionSetName = "_globalOptionSetName",

        Value = 100011

    };

 

// Execute the request.

_service.Execute(deleteOptionValueRequest

CreateManyToManyRequest

// ** CreateManyToManyRequest **

//Ex: creates the entity relationship between the Account and Contact entities by using CreateManyToManyRequest.

 

CreateManyToManyRequest createManyToManyRelationshipRequest = new CreateManyToManyRequest

    {

        IntersectEntitySchemaName = "new_accounts_campaigns",

        ManyToManyRelationship = new ManyToManyRelationshipMetadata

        {

            SchemaName = "new_accounts_campaigns",

            Entity1LogicalName = "account",

            Entity1AssociatedMenuConfiguration =

            new AssociatedMenuConfiguration

            {

                Behavior = AssociatedMenuBehavior.UseLabel,

                Group = AssociatedMenuGroup.Details,

                Label = new Label("Account", 1033),

                Order = 10000

            },

            Entity2LogicalName = "campaign",

            Entity2AssociatedMenuConfiguration =

            new AssociatedMenuConfiguration

            {

                Behavior = AssociatedMenuBehavior.UseLabel,

                Group = AssociatedMenuGroup.Details,

                Label = new Label("Campaign", 1033),

                Order = 10000

            }

        }

    };

 

CreateManyToManyResponse createManytoManyRelationshipResponse =

    (CreateManyToManyResponse)_service.Execute(

    createManyToManyRelationshipRequest);

 


Complete DateDiff() Function

Perhaps the above function looks like the Visual Basic function of the same name. In fact it is loosely based on it. I was planning on recreating it in its complete form for your enjoyment, but, thankfully someone has already beat me to it. That someone is Rob Eberhardt of Slingshot Solutions. It's part of his excellent jsDate script. It's free to use as long as you give credit where credit is due. His function offers a lot of advantages over the simple one presented above. For starters, his can calculate the month interval, which cannot be done by dividing into the number of milliseconds since month lengths differ. It also supports setting the first day of the week to something other than Sunday. Finally, it adjusts for Daylight Savings Time, which affects intervals of a day ("d") and larger:
Date.DateDiff = function(p_Interval, p_Date1, p_Date2, p_FirstDayOfWeek){
 p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek);

 var dt1 = Date.CDate(p_Date1);
 var dt2 = Date.CDate(p_Date2);

 //correct Daylight Savings Ttime (DST)-affected intervals ("d" & bigger)
 if("h,n,s,ms".indexOf(p_Interval.toLowerCase())==-1){
  if(p_Date1.toString().indexOf(":") ==-1){ dt1.setUTCHours(0,0,0,0) }; // no time, assume 12am
  if(p_Date2.toString().indexOf(":") ==-1){ dt2.setUTCHours(0,0,0,0) }; // no time, assume 12am
 }


 // get ms between UTC dates and make into "difference" date
 var iDiffMS = dt2.valueOf() - dt1.valueOf();
 var dtDiff = new Date(iDiffMS);

 // calc various diffs
 var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
 var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
 var nQuarters = parseInt(nMonths / 3);
 
 var nMilliseconds = iDiffMS;
 var nSeconds = parseInt(iDiffMS / 1000);
 var nMinutes = parseInt(nSeconds / 60);
 var nHours = parseInt(nMinutes / 60);
 var nDays  = parseInt(nHours / 24); //now fixed for DST switch days
 var nWeeks = parseInt(nDays / 7);

 if(p_Interval.toLowerCase()=='ww'){
   // set dates to 1st & last FirstDayOfWeek
   var offset = Date.DatePart("w", dt1, p_FirstDayOfWeek)-1;
   if(offset){ dt1.setDate(dt1.getDate() +7 -offset); }
   var offset = Date.DatePart("w", dt2, p_FirstDayOfWeek)-1;
   if(offset){ dt2.setDate(dt2.getDate() -offset); }
   // recurse to "w" with adjusted dates
   var nCalWeeks = Date.DateDiff("w", dt1, dt2) + 1;
 }
 
 // return difference
 switch(p_Interval.toLowerCase()){
  case "yyyy": return nYears;
  case "q": return nQuarters;
  case "m": return nMonths;
  case "y": // day of year
  case "d": return nDays;
  case "w": return nWeeks;
  case "ww":return nCalWeeks; // week of year 
  case "h": return nHours;
  case "n": return nMinutes;
  case "s": return nSeconds;
  case "ms":return nMilliseconds;
  default : return "invalid interval: '" + p_Interval + "'";
 }
}
var y2k  = new Date(2000, 0, 1) //Month is 0-11 in JavaScript!
var today= new Date();
console.log('Months since the new millenium: ' + Date.DateDiff('m', y2k, today)); //displays 143

A Simple dateDiff() Function

There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where 'w' is a week, 'd' a day, 'h' hours, 'n' for minutes, and 's' for seconds:

// datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'
Date.dateDiff = function(datepart, fromdate, todate) { 
  datepart = datepart.toLowerCase(); 
  var diff = todate - fromdate; 
  var divideBy = { w:604800000, 
                   d:86400000, 
                   h:3600000, 
                   n:60000, 
                   s:1000 }; 
  
  return Math.floor( diff/divideBy[datepart]);
}
//Set the two dates
var y2k  = new Date(2000, 0, 1);
var today= new Date();
console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 625

Converting Milliseconds to other Intervals

As long as you can calculate the number of milliseconds in an interval, you can come up with a number by dividing the total number of milliseconds by the number of milliseconds in the desired interval. What's more, we can apply the modulus (%) operator to strip out that value to determine the next larger interval. The key is to always go from the smallest interval - milliseconds - to the largest - days:

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
  //take out milliseconds
  difference_ms = difference_ms/1000;
  var seconds = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var minutes = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var hours = Math.floor(difference_ms % 24);  
  var days = Math.floor(difference_ms/24);
  
  return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
}

//Set the two dates
var y2k  = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds"
console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):
 
Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
    
  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));
The rounding is optional, depending on whether you want partial days or not.

jsDate: VBScript native Date functions emulated for Javascript

/*
Name: jsDate
Desc: VBScript native Date functions emulated for Javascript
Author: Rob Eberhardt, Slingshot Solutions - http://slingfive.com/
Note: see jsDate.txt for more info
*/

// constants
vbGeneralDate=0; vbLongDate=1; vbShortDate=2; vbLongTime=3; vbShortTime=4;  // NamedFormat
vbUseSystemDayOfWeek=0; vbSunday=1; vbMonday=2; vbTuesday=3; vbWednesday=4; vbThursday=5; vbFriday=6; vbSaturday=7; // FirstDayOfWeek
vbUseSystem=0; vbFirstJan1=1; vbFirstFourDays=2; vbFirstFullWeek=3; // FirstWeekOfYear

// arrays (1-based)
Date.MonthNames = [null,'January','February','March','April','May','June','July','August','September','October','November','December'];
Date.WeekdayNames = [null,'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];




Date.IsDate = function(p_Expression){
 return !isNaN(new Date(p_Expression));  // <-- review further
}

Date.CDate = function(p_Date){
 if(Date.IsDate(p_Date)){ return new Date(p_Date); }

 var strTry = p_Date.replace(/\-/g, '/').replace(/\./g, '/').replace(/ /g, '/'); // fix separators
 strTry = strTry.replace(/pm$/i, " pm").replace(/am$/i, " am"); // and meridian spacing
 if(Date.IsDate(strTry)){ return new Date(strTry); }

 var strTryYear = strTry + '/' + new Date().getFullYear(); // append year
 if(Date.IsDate(strTryYear)){ return new Date(strTryYear); }
 

 if(strTry.indexOf(":")){ // if appears to have time
  var strTryYear2 = strTry.replace(/ /, '/' + new Date().getFullYear() + ' '); // insert year
  if(Date.IsDate(strTryYear2)){ return new Date(strTryYear2); }

  var strTryDate = new Date().toDateString() + ' ' + p_Date; // pre-pend current date
  if(Date.IsDate(strTryDate)){ return new Date(strTryDate); }
 }
 
 return false; // double as looser IsDate
 //throw("Error #13 - Type mismatch"); // or is this better? 
}
 


Date.DateAdd = function(p_Interval, p_Number, p_Date){
 if(!Date.CDate(p_Date)){ return "invalid date: '" + p_Date + "'"; }
 if(isNaN(p_Number)){ return "invalid number: '" + p_Number + "'"; } 

 p_Number = new Number(p_Number);
 var dt = Date.CDate(p_Date);
 
 switch(p_Interval.toLowerCase()){
  case "yyyy": {
   dt.setFullYear(dt.getFullYear() + p_Number);
   break;
  }
  case "q": {
   dt.setMonth(dt.getMonth() + (p_Number*3));
   break;
  }
  case "m": {
   dt.setMonth(dt.getMonth() + p_Number);
   break;
  }
  case "y":   // day of year
  case "d":   // day
  case "w": {  // weekday
   dt.setDate(dt.getDate() + p_Number);
   break;
  }
  case "ww": { // week of year
   dt.setDate(dt.getDate() + (p_Number*7));
   break;
  }
  case "h": {
   dt.setHours(dt.getHours() + p_Number);
   break;
  }
  case "n": {  // minute
   dt.setMinutes(dt.getMinutes() + p_Number);
   break;
  }
  case "s": {
   dt.setSeconds(dt.getSeconds() + p_Number);
   break;
  }
  case "ms": { // JS extension
   dt.setMilliseconds(dt.getMilliseconds() + p_Number);
   break;
  }
  default: {
   return "invalid interval: '" + p_Interval + "'";
  }
 }
 return dt;
}



Date.DateDiff = function(p_Interval, p_Date1, p_Date2, p_FirstDayOfWeek){
 if(!Date.CDate(p_Date1)){ return "invalid date: '" + p_Date1 + "'"; }
 if(!Date.CDate(p_Date2)){ return "invalid date: '" + p_Date2 + "'"; }
 p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek); // set default & cast

 var dt1 = Date.CDate(p_Date1);
 var dt2 = Date.CDate(p_Date2);

 // correct DST-affected intervals ("d" & bigger)
 if("h,n,s,ms".indexOf(p_Interval.toLowerCase())==-1){
  if(p_Date1.toString().indexOf(":") ==-1){ dt1.setUTCHours(0,0,0,0) }; // no time, assume 12am
  if(p_Date2.toString().indexOf(":") ==-1){ dt2.setUTCHours(0,0,0,0) }; // no time, assume 12am
 }


 // get ms between UTC dates and make into "difference" date
 var iDiffMS = dt2.valueOf() - dt1.valueOf();
 var dtDiff = new Date(iDiffMS);

 // calc various diffs
 var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
 var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
 var nQuarters = parseInt(nMonths / 3); //<<-- different than VBScript, which watches rollover not completion
 
 var nMilliseconds = iDiffMS;
 var nSeconds = parseInt(iDiffMS / 1000);
 var nMinutes = parseInt(nSeconds / 60);
 var nHours = parseInt(nMinutes / 60);
 var nDays  = parseInt(nHours / 24); // <-- now fixed for DST switch days
 var nWeeks = parseInt(nDays / 7);


 if(p_Interval.toLowerCase()=='ww'){
   // set dates to 1st & last FirstDayOfWeek
   var offset = Date.DatePart("w", dt1, p_FirstDayOfWeek)-1;
   if(offset){ dt1.setDate(dt1.getDate() +7 -offset); }
   var offset = Date.DatePart("w", dt2, p_FirstDayOfWeek)-1;
   if(offset){ dt2.setDate(dt2.getDate() -offset); }
   // recurse to "w" with adjusted dates
   var nCalWeeks = Date.DateDiff("w", dt1, dt2) + 1;
 }
 // TODO: similar for 'w'?
 
 
 // return difference
 switch(p_Interval.toLowerCase()){
  case "yyyy": return nYears;
  case "q": return nQuarters;
  case "m": return nMonths;
  case "y":   // day of year
  case "d": return nDays;
  case "w": return nWeeks;
  case "ww":return nCalWeeks; // week of year 
  case "h": return nHours;
  case "n": return nMinutes;
  case "s": return nSeconds;
  case "ms":return nMilliseconds; // not in VBScript
  default : return "invalid interval: '" + p_Interval + "'";
 }
}




Date.DatePart = function(p_Interval, p_Date, p_FirstDayOfWeek){
 if(!Date.CDate(p_Date)){ return "invalid date: '" + p_Date + "'"; }

 var dtPart = Date.CDate(p_Date);
 
 switch(p_Interval.toLowerCase()){
  case "yyyy": return dtPart.getFullYear();
  case "q": return parseInt(dtPart.getMonth() / 3) + 1;
  case "m": return dtPart.getMonth() + 1;
  case "y": return Date.DateDiff("y", "1/1/" + dtPart.getFullYear(), dtPart) + 1; // day of year
  case "d": return dtPart.getDate();
  case "w": return Date.Weekday(dtPart.getDay()+1, p_FirstDayOfWeek);  // weekday
  case "ww":return Date.DateDiff("ww", "1/1/" + dtPart.getFullYear(), dtPart, p_FirstDayOfWeek) + 1; // week of year
  case "h": return dtPart.getHours();
  case "n": return dtPart.getMinutes();
  case "s": return dtPart.getSeconds();
  case "ms":return dtPart.getMilliseconds(); // <-- JS extension, NOT in VBScript
  default : return "invalid interval: '" + p_Interval + "'";
 }
}



Date.MonthName = function(p_Month, p_Abbreviate){
 if(isNaN(p_Month)){ // v0.94- compat: extract real param from passed date
  if(!Date.CDate(p_Month)){ return "invalid month: '" + p_Month + "'"; }
  p_Month = DatePart("m", Date.CDate(p_Month));
 }

 var retVal = Date.MonthNames[p_Month];
 if(p_Abbreviate==true){ retVal = retVal.substring(0, 3) } // abbr to 3 chars
 return retVal;
}


Date.WeekdayName = function(p_Weekday, p_Abbreviate, p_FirstDayOfWeek){
 if(isNaN(p_Weekday)){ // v0.94- compat: extract real param from passed date
  if(!Date.CDate(p_Weekday)){ return "invalid weekday: '" + p_Weekday + "'"; }
  p_Weekday = DatePart("w", Date.CDate(p_Weekday));
 }
 p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek); // set default & cast

 var nWeekdayNameIdx = ((p_FirstDayOfWeek-1 + parseInt(p_Weekday)-1 +7) % 7) + 1; // compensate nWeekdayNameIdx for p_FirstDayOfWeek
 var retVal = Date.WeekdayNames[nWeekdayNameIdx];
 if(p_Abbreviate==true){ retVal = retVal.substring(0, 3) } // abbr to 3 chars
 return retVal;
}


// adjusts weekday for week starting on p_FirstDayOfWeek
Date.Weekday=function(p_Weekday, p_FirstDayOfWeek){ 
 p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek); // set default & cast

 return ((parseInt(p_Weekday) - p_FirstDayOfWeek +7) % 7) + 1;
}





Date.FormatDateTime = function(p_Date, p_NamedFormat){
 if(p_Date.toUpperCase().substring(0,3) == "NOW"){ p_Date = new Date() };
 if(!Date.CDate(p_Date)){ return "invalid date: '" + p_Date + "'"; }
 if(isNaN(p_NamedFormat)){ p_NamedFormat = vbGeneralDate };

 var dt = Date.CDate(p_Date);

 switch(parseInt(p_NamedFormat)){
  case vbGeneralDate: return dt.toString();
  case vbLongDate:  return Format(p_Date, 'DDDD, MMMM D, YYYY');
  case vbShortDate:  return Format(p_Date, 'MM/DD/YYYY');
  case vbLongTime:  return dt.toLocaleTimeString();
  case vbShortTime:  return Format(p_Date, 'HH:MM:SS');
  default: return "invalid NamedFormat: '" + p_NamedFormat + "'";
 }
}


Date.Format = function(p_Date, p_Format, p_FirstDayOfWeek, p_firstweekofyear) {
 if(!Date.CDate(p_Date)){ return "invalid date: '" + p_Date + "'"; }
 if(!p_Format || p_Format==''){ return dt.toString() };

 var dt = Date.CDate(p_Date);

 // Zero-padding formatter
 this.pad = function(p_str){
  if(p_str.toString().length==1){p_str = '0' + p_str}
  return p_str;
 }

 var ampm = dt.getHours()>=12 ? 'PM' : 'AM'
 var hr = dt.getHours();
 if (hr == 0){hr = 12};
 if (hr > 12) {hr -= 12};
 var strShortTime = hr +':'+ this.pad(dt.getMinutes()) +':'+ this.pad(dt.getSeconds()) +' '+ ampm;
 var strShortDate = (dt.getMonth()+1) +'/'+ dt.getDate() +'/'+ new String( dt.getFullYear() ).substring(2,4);
 var strLongDate = Date.MonthName(dt.getMonth()+1) +' '+ dt.getDate() +', '+ dt.getFullYear();  //

 var retVal = p_Format;
 
 // switch tokens whose alpha replacements could be accidentally captured
 retVal = retVal.replace( new RegExp('C', 'gi'), 'CCCC' ); 
 retVal = retVal.replace( new RegExp('mmmm', 'gi'), 'XXXX' );
 retVal = retVal.replace( new RegExp('mmm', 'gi'), 'XXX' );
 retVal = retVal.replace( new RegExp('dddddd', 'gi'), 'AAAAAA' ); 
 retVal = retVal.replace( new RegExp('ddddd', 'gi'), 'AAAAA' ); 
 retVal = retVal.replace( new RegExp('dddd', 'gi'), 'AAAA' );
 retVal = retVal.replace( new RegExp('ddd', 'gi'), 'AAA' );
 retVal = retVal.replace( new RegExp('timezone', 'gi'), 'ZZZZ' );
 retVal = retVal.replace( new RegExp('time24', 'gi'), 'TTTT' );
 retVal = retVal.replace( new RegExp('time', 'gi'), 'TTT' );

 // now do simple token replacements
 retVal = retVal.replace( new RegExp('yyyy', 'gi'), dt.getFullYear() );
 retVal = retVal.replace( new RegExp('yy', 'gi'), new String( dt.getFullYear() ).substring(2,4) );
 retVal = retVal.replace( new RegExp('y', 'gi'), Date.DatePart("y", dt) );
 retVal = retVal.replace( new RegExp('q', 'gi'), Date.DatePart("q", dt) );
 retVal = retVal.replace( new RegExp('mm', 'gi'), (dt.getMonth() + 1) ); 
 retVal = retVal.replace( new RegExp('m', 'gi'), (dt.getMonth() + 1) ); 
 retVal = retVal.replace( new RegExp('dd', 'gi'), this.pad(dt.getDate()) );
 retVal = retVal.replace( new RegExp('d', 'gi'), dt.getDate() );
 retVal = retVal.replace( new RegExp('hh', 'gi'), this.pad(dt.getHours()) );
 retVal = retVal.replace( new RegExp('h', 'gi'), dt.getHours() );
 retVal = retVal.replace( new RegExp('nn', 'gi'), this.pad(dt.getMinutes()) );
 retVal = retVal.replace( new RegExp('n', 'gi'), dt.getMinutes() );
 retVal = retVal.replace( new RegExp('ss', 'gi'), this.pad(dt.getSeconds()) ); 
 retVal = retVal.replace( new RegExp('s', 'gi'), dt.getSeconds() ); 
 retVal = retVal.replace( new RegExp('t t t t t', 'gi'), strShortTime ); 
 retVal = retVal.replace( new RegExp('am/pm', 'g'), dt.getHours()>=12 ? 'pm' : 'am');
 retVal = retVal.replace( new RegExp('AM/PM', 'g'), dt.getHours()>=12 ? 'PM' : 'AM');
 retVal = retVal.replace( new RegExp('a/p', 'g'), dt.getHours()>=12 ? 'p' : 'a');
 retVal = retVal.replace( new RegExp('A/P', 'g'), dt.getHours()>=12 ? 'P' : 'A');
 retVal = retVal.replace( new RegExp('AMPM', 'g'), dt.getHours()>=12 ? 'pm' : 'am');
 // (always proceed largest same-lettered token to smallest)

 // now finish the previously set-aside tokens 
 retVal = retVal.replace( new RegExp('XXXX', 'gi'), Date.MonthName(dt.getMonth()+1, false) ); //
 retVal = retVal.replace( new RegExp('XXX',  'gi'), Date.MonthName(dt.getMonth()+1, true ) ); //
 retVal = retVal.replace( new RegExp('AAAAAA', 'gi'), strLongDate ); 
 retVal = retVal.replace( new RegExp('AAAAA', 'gi'), strShortDate ); 
 retVal = retVal.replace( new RegExp('AAAA', 'gi'), Date.WeekdayName(dt.getDay()+1, false, p_FirstDayOfWeek) ); // 
 retVal = retVal.replace( new RegExp('AAA',  'gi'), Date.WeekdayName(dt.getDay()+1, true,  p_FirstDayOfWeek) ); // 
 retVal = retVal.replace( new RegExp('TTTT', 'gi'), dt.getHours() + ':' + this.pad(dt.getMinutes()) );
 retVal = retVal.replace( new RegExp('TTT',  'gi'), hr +':'+ this.pad(dt.getMinutes()) +' '+ ampm );
 retVal = retVal.replace( new RegExp('CCCC', 'gi'), strShortDate +' '+ strShortTime ); 

 // finally timezone
 tz = dt.getTimezoneOffset();
 timezone = (tz<0) ? ('GMT-' + tz/60) : (tz==0) ? ('GMT') : ('GMT+' + tz/60);
 retVal = retVal.replace( new RegExp('ZZZZ', 'gi'), timezone );

 return retVal;
}



// ====================================

/* if desired, map new methods to direct functions
*/
IsDate = Date.IsDate;
CDate = Date.CDate;
DateAdd = Date.DateAdd;
DateDiff = Date.DateDiff;
DatePart = Date.DatePart;
MonthName = Date.MonthName;
WeekdayName = Date.WeekdayName;
Weekday = Date.Weekday;
FormatDateTime = Date.FormatDateTime;
Format = Date.Format;



/* and other capitalizations for easier porting
isDate = IsDate;
dateAdd = DateAdd;
dateDiff = DateDiff;
datePart = DatePart;
monthName = MonthName;
weekdayName = WeekdayName;
formatDateTime = FormatDateTime;
format = Format;

isdate = IsDate;
dateadd = DateAdd;
datediff = DateDiff;
datepart = DatePart;
monthname = MonthName;
weekdayname = WeekdayName;
formatdatetime = FormatDateTime;

ISDATE = IsDate;
DATEADD = DateAdd;
DATEDIFF = DateDiff;
DATEPART = DatePart;
MONTHNAME = MonthName;
WEEKDAYNAME = WeekdayName;
FORMATDATETIME = FormatDateTime;
FORMAT = Format;
*/

Update Message

Updates an instance of an entity.

  
//# The following code example shows how to use the Update message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the account object.
account account = new account();

// Set the properties of the account object to be updated.
account.address1_line1 = "34 Market St.";
account.creditlimit = new CrmMoney();
account.creditlimit.Value = 500000;

// accountid is a key that references the ID of the account to be updated.
account.accountid = new Key();
// accountid.Value is the GUID of the record to be changed.
account.accountid.Value = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the target object for the request.
TargetUpdateAccount target = new TargetUpdateAccount();

// Set the properties of the target object.
target.Account = account;

// Create the request object.
UpdateRequest update = new UpdateRequest();

// Set the properties of the request object.
update.Target = target;

// Execute the request.
UpdateResponse updated = (UpdateResponse)service.Execute(update);





CanBeReferencingRequest

// ** CanBeReferencingRequest **

//Checks whether the specified entity can be the referencing entity in one-to-many

//relationship.

// REQUEST

CanBeReferencingRequest canBereferencingRequest = new CanBeReferencingRequest

{

    EntityName = "referencingEntity(Referencing Entity)"

};

 

// RESPONSE

CanBeReferencingResponse canBeReferencingResponse =

    (CanBeReferencingResponse)_service.Execute(canBereferencingRequest);

 

// Verify RESPONSE

if (!canBeReferencingResponse.CanBeReferencing)

{

    Console.WriteLine(

        "Entity {0} can't be the referencing entity in this one-to-many relationship",

        "referencingEntity(Referencing Entity)");

}


Create a memo attribute

// ** Create a memo attribute **

MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata

{

    // Set base properties

    SchemaName = "new_memo",

    DisplayName = new Label("Sample Memo", 1033),

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    Description = new Label("Memo Attribute", 1033),

    // Set extended properties

    Format = StringFormat.TextArea,

    ImeMode = ImeMode.Disabled,

    MaxLength = 500

};

 

 

// Create the request.

CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest

{

    EntityName = "EntityLogicalName",

    Attribute = memoAttribute

};

 

// Execute the request. Get Response

CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest); 

 


CanBeReferenced Entity Request

// ** CanBeReferenced Entity Request **

//Checks whether the specified entity can be the primary entity in one-to-many relationship.

// REQUEST

CanBeReferencedRequest canBeReferencedRequest = new CanBeReferencedRequest

{

    EntityName = "referencedEntity(Primary Entity)" //Primary Entity Name

};

 

// RESPONSE

CanBeReferencedResponse canBeReferencedResponse =

    (CanBeReferencedResponse)_service.Execute(canBeReferencedRequest);

 

// Verify RESPONSE

if (!canBeReferencedResponse.CanBeReferenced)

{

    Console.WriteLine(

        "Entity {0} can't be the primary entity in this one-to-many relationship",

        "referencedEntity(Primary Entity)");

}

Create Entity request


// ** Create Entity request **

// Desc: Creates an entity in the current Organization

CreateEntityRequest cent = new CreateEntityRequest();

// Entity Metadata

cent.Entity = new Microsoft.Xrm.Sdk.Metadata.EntityMetadata(){

    SchemaName = "_customEntity",

    DisplayName = new Label("_custom",1033),

    DisplayCollectionName = new Label("_customentities",1033),

    Description = new Label("created using Entity request",1033),

    OwnershipType = OwnershipTypes.OrganizationOwned,

    IsActivity=false

};

// Attribute metadata

cent.PrimaryAttribute = new StringAttributeMetadata()

{

    SchemaName = "new_accountname",

    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

    MaxLength = 100,

    Format = StringFormat.Text,

    DisplayName = new Label("Account Name", 1033),

    Description = new Label("The primary attribute for the Bank Account entity.", 1033)

};

 

// Executes the request(Org service)

_service.Execute(cent);

 

Ajax Programming


var http_request = false;
  var ser = Math.round(Math.random()*1000000); // Anti-caching serial number
  var debug = false; // Set to true to show the full server response
  
  function ajax(httpRequestMethod, url, parameters, target)
  {
    http_request = false;
    document.getElementById(target).innerHTML = 'Wait...'
    if (window.XMLHttpRequest)
    { // For Mozilla, Safari, Opera, IE7
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType)
      {
        http_request.overrideMimeType('text/plain');
        //Change MimeType to match the data type of the server response.
        //Examples: "text/xml", "text/html", "text/plain"
      }
    }
    else if (window.ActiveXObject)
    { // For IE6
      try
      {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e)
      {
        try
        {
          http_request = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {}
      }
    }
    if (!http_request)
    {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    http_request.onreadystatechange = function() {updateElement(target);};
    if (httpRequestMethod == 'GET')
    {
      http_request.open('GET', url + '?' + parameters, true);
      http_request.send(null);
      ser = ser + 1;
    }
    else if (httpRequestMethod == 'POST')
    {
      http_request.open('POST', url, true);
      http_request.setRequestHeader('Content-Type',
        'application/x-www-form-urlencoded');
      http_request.send(parameters);
    }
    else
    {
      alert('Sorry, unsupported HTTP method');
    }
  }

  function updateElement(target)
  {
    if (http_request.readyState == 4)
    {
      if (debug == true)
      {
        alert(http_request.responseText);
      }
      if (http_request.status == 200)
      {
        document.getElementById(target).innerHTML =
          http_request.responseText;
      }
      else if (debug == false)
      {
        alert('The server returned an error. Please set debug = true to see the full server response.');
      }
    }
  }
  

XMLHttpRequest

Summary of the specification by W3C, and usage
This server side object is used by JavaScript to exchange data with the server, in plain text, XML or JSON format. The XML format is automatically parsed by the object at loading and accessible by DOM's methods. JSON files are parsed by the eval() JavaScript command. In Internet Explorer, it is an Active X object.

 

Brief history 

XMLHttpRequest, was first implemented by Internet Explorer since the 4.0 version. The same concept was named XMLHTTP some times, before the Ajax name becomes commonly used. The use of XMLHttpRequest in 2005 by Google, in Gmail and GoogleMaps has contributed to the success of this technology.

 

Description 

This is a class that is recognized by all current browsers, and by the JavaScript client side programming language. For each request to the server, a new instance is created by a call to the constructor. The open method starts the connection, in read or write mode, to receive data from the server or send it. It will be processed by the server with a server side language as PHP, Java, etc...
The connection takes several successive states that are assigned to the readyState attribute of the object. When the final state is reached, the data may be found in another attribute. It may be a plain text or an XML document. The JSON format is loaded as plain text and parsed by JavaScript. More details on the use of the class in the Ajax tutorial.

 

Attributes 

The purpose of attributes of the class is to be assigned the status of the connection, and to hold data.

unsigned short readyState 

The code successively changes value until the server is ready, from 0 to 4 .
0 Not initialized
1 Open
2 Sent
3 Received
4 Loaded

status(unsigned short) 

200 is ok
404 if the page is not found.

statusText(DOMString) 

Holds the label of the status, corresponding to the status code.

responseText(DOMString)

 Holds loaded data as a string of characters. It is completely filled when the status is 4.

responseXml(DOMDocument) 

Holds an XML loaded file, and DOM's methods allow to extract data. It is filled only when the code is 4 and null otherwise.

onreadystatechange(EventListener) 

Invoked when readyState is assigned.

 

Methods

 Apart the constructor, the class has two main methods, open to create a session and designate the distant file, and send to move data to the server.

abort() 

Resets the object and stops any activity created by the object.

getAllResponseHeaders() 

 Return all headers into a string, separated by CR and LF codes.

getResponseHeader(DOMString) 

Return the header of data received, after the last request. Several headers should be separated by a comma plus a space.

open(mode, url, boolean [,login, password]) 

mode: type of request, GET, POST, HEAD or other http methods.
 url: the location of the file, with a path. boolean: true (asynchronous) / false (synchronous). optionally, a login and a password as additional arguments.

send("string") 

null or empty with a GET command, a string otherwise. Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not1. setRequestHeader(DOMString,DomString) Arguments are the name of the header and the value. Several values may be successively sent. Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not 1.

How to use XMLHttpRequest 

The class is a part of ECMAScript (JavaScript) and used as any other class of the language, but there are several constructors according to the browser. Here is a complete code to open an Ajax session, by creating a new XMLHttpRequest object and loading some data. The code may be tested with several demos on the Ajax tutorial and in the Ajax sub-domain.
function submitForm()
{
    var xhr=null;
    try
    {
        xhr = new XMLHttpRequest();
    } 
    catch(e)
    {
        try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e2)
        {
            try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) {}
    }
}

xhr.onreadystatechange = function(){
    document.ajax.dyn.value="Wait server...";
    if(xhr.readyState == 4)
    {
        if(xhr.status == 200)
        {
            document.ajax.dyn.value="Received:" +
            xhr.responseText;
        }
        else
        {
            document.ajax.dyn.value="Error: returned statuscode " + xhr.status + " " + xhr.statusText;
        }
    }
};
xhr.open("GET", "data.xml", true);
xhr.send(null);
} 
 

 

Caching problem 

Memory cache does not work properly with the object. Often, the file loaded by the GET method is not the last version, but an older version taken from the memory buffer. If the file is not too big, this can be overcomed easily by adding a parameter to the command. Replace: xhr.open("GET", "data.xml", true); by: xhr.open("GET", "data.xml?nocache=" + Math.random(),true);

The HTML format 

We can load XML files, can we load also HTML or XHTML files? Actually, this is planned for the next specification of the XMLHttpRequest object as it is planned to access cross-domains files. It is planned that, in this case, the text/html mime type will be used, while the text/xml type is used for XML documents, in the content type header. For now, a replacing solution exists, the pseudo responseHTML attribute, that is given on this site.

Specification 

W3C Working Draft specification for XMLHttpRequest. The W3C is working on a new version of the standard, called XMLHttpRequest Level 2. New improvements are cross-site requests, progress events, and the handling of byte streams for both sending and receiving. Besides the XMLHttpRequest object itself, W3C has established a specification for cross-site exchanges named Access Control. However Microsoft has choosen to not support the proptocol and offers in Internet Explorer 8 an alternative named XDomainRequest. This object could replace XMLHttpRequest or not depending its support for all features of XHR in the final version.

CRM 4.0 PLuGIN: sample plugin with pre & post Images

p u b l i c v o i d E x e c u t e ( I P l u g i n E x e c u t i o n C o n t e x t c o n t e x t )
{
s t r i n g m _ O p p o r t u n i t y N ame = s t r i n g . E mp t y ;
s t r i n g m _ O p p o r t u n i t y I d = s t r i n g . E mp t y ;
i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " C r e a t e " ) )
{
/ / E n t i t y c r e a t i o n . D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{
K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}
e l s e i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " U p d a t e " ) )
{
/ / E n t i t y u p d a t e . D y n am i c E n t i t y p r e t E n t i t y ;
D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P r e E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p r e t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P r e E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{ K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}

Add Button in CRM Form

 
/* Jscript: Add button in CRM */


function ConvertToButton(fieldname, buttontext, buttonwidth,clickevent, title)

{

//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";
}
}



// now the definition of the function to call on button click

function FunctionName()

{

// do something

}

Deserialize XML into an Instance of BusinessEntity

You may have a scenario where an XML representation of a BusinessEntity class needs to be parsed into an in-memory object. One example is parsing the XML representation of DynamicEntity into an instance of this class within a plug-in assembly.

This sample is a stand-alone application that demonstrates how this can be done. Included here are two sample XML files that can be successfully parsed by this application. The sample parses any BusinessEntity XML string, and if the entity is of the type DynamicEntity, its properties are printed to the console. Child entities such as calendar rules on a calendar are handled as well.



namespace CrmClient
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using DynamicEntity.CrmServer;

class App
{
public static void Main(string[] args)
{
App theApp = new App(args);

theApp.Run();
}

public App(string[] args)
{
_args = args;
}

private void Run()
{
if (_args.Length < 1)
{
Console.WriteLine("Usage: DynamicEntityTest ");
return;
}

string fileName = _args[0];
Console.WriteLine("Reading XML from file {0}", fileName);

// Use stream reader to display XML to be parsed.
StreamReader sr = new StreamReader(fileName);
string entityXml = sr.ReadToEnd();
Console.WriteLine("XML to be parsed:");
Console.WriteLine(new string('-', 60));
Console.WriteLine("{0}", entityXml);
Console.WriteLine(new string('-', 60));

// Re-open the stream so that position is at the beginning of XML.
sr = new StreamReader(fileName);

// De-serialize the XML stream using the .NET XmlSerializer class.
XmlRootAttribute root = new XmlRootAttribute("BusinessEntity");
root.Namespace
= "http://schemas.microsoft.com/crm/2006/WebServices";
XmlSerializer xmlSerializer
= new XmlSerializer(typeof(BusinessEntity), root);
BusinessEntity entity
= (BusinessEntity)xmlSerializer.Deserialize(sr);
// End of deserialization.

Console.WriteLine("Deserialized XML into object of type {0}",
entity.GetType().FullName);

DynamicEntity dynamicEntity = entity as DynamicEntity;
if (dynamicEntity != null)
{
DisplayDynamicEntity(dynamicEntity,
"de-serialized from XML string");
}
}

///
/// Displays DynamicEntity instance and its properties.
///

private void DisplayDynamicEntity(DynamicEntity entity,
string message)
{
const string LineFormat = " {0,-30}{1,-30}{2}";

Console.WriteLine("DynamicEntity {0}: {1} with {2} properties:",
message, entity.Name, entity.Properties.Length);

Console.WriteLine(LineFormat, "Property Name", "Property Type",
"Property Value");
Console.WriteLine(LineFormat, "---", "---", "---");

foreach (Property prop in entity.Properties)
{
Type propertyType = prop.GetType();

// Format property value based on property type.
string propertyValue = string.Empty;
if (propertyType == typeof(StringProperty))
{
propertyValue = string.Format("'{0}'",
((StringProperty)prop).Value);
}
else if (propertyType == typeof(CrmDateTimeProperty))
{
CrmDateTime dt = ((CrmDateTimeProperty)prop).Value;
propertyValue
= string.Format("'{0}' date='{1}' time='{2}'",
dt.Value, dt.date, dt.time);
}
else if (propertyType == typeof(KeyProperty))
{
Key key = ((KeyProperty)prop).Value;
propertyValue = string.Format("'{0:D}'", key.Value);
}
else if (propertyType == typeof(LookupProperty))
{
Lookup lookup = ((LookupProperty)prop).Value;
propertyValue
= string.Format("'{0:D}' name='{1}' dsc='{2}'",
lookup.Value, lookup.name, lookup.dsc);
}
else if (propertyType == typeof(StateProperty))
{
string state = ((StateProperty)prop).Value;
propertyValue = string.Format("'{0}'", state);
}
else if (propertyType == typeof(DynamicEntityArrayProperty))
{
DynamicEntity[] children
= ((DynamicEntityArrayProperty)prop).Value;
propertyValue
= string.Format("number of child entities: {0}",
children.Length);

Console.WriteLine(LineFormat, prop.Name, propertyType.Name,
propertyValue);

Console.WriteLine(new string('>', 30));

int nc = 1;
foreach (DynamicEntity child in children)
{
DisplayDynamicEntity(child,
message + " - child #" + nc.ToString());
nc++;
}

Console.WriteLine(new string('<', 30));

continue;
}
else if (propertyType == typeof(OwnerProperty))
{
Owner owner = ((OwnerProperty)prop).Value;
propertyValue
= string.Format("'{0}' name='{1}' type='{2}'",
owner.Value, owner.name, owner.type);
}
else if (propertyType == typeof(CrmBooleanProperty))
{
CrmBoolean boolean = ((CrmBooleanProperty)prop).Value;
propertyValue = string.Format("'{0}'", boolean.Value);
}
else if (propertyType == typeof(PicklistProperty))
{
Picklist picklist = ((PicklistProperty)prop).Value;
propertyValue
= string.Format("'{0}', name='{1}'", picklist.Value,
picklist.name);
}

Console.WriteLine(LineFormat, prop.Name, propertyType.Name,
propertyValue);
}
}

string[] _args;
}
}


CRM 2011 CS: Assigning Lookup value

C# assign the contact to an account.
//C# assign the contact to an account.

Entity account = new Entity("account");
account["name"] = "Test Account1";
EntityReference primaryContactId = new EntityReference("contact", contactId);
account["primarycontactid"] = primaryContactId;

CRM 2011 CS: get String from a Lookup Field in crm 2011

//C# get String from a Lookup Field in crm 2011

((EntityReference)item.Attributes["new_lookup"]).Name

 

//C# get ID from a Lookup Field in crm 2011

((EntityReference)item.Attributes["new_lookup"]).Id