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

Monday, October 15, 2012

CRM 2011 JS: Change Subgrid View JScript


// Change Subgrid View Java Script

Change the Fetch XML and set the subgrid ID
function UpdateSubGrid()
{
var leadGrid = document.getElementById("Contact");//Set Subgrid ID
//If this method is called from the form OnLoad, make sure that the grid is loaded before proceeding
if (leadGrid.readyState != "complete")
{
//The subgrid hasn't loaded, wait 1 second and then try again
setTimeout('UpdateLeadSubGrid()', 1000);
return;
}


var fetchXml = " ";//Set Fetch XML
//Inject the new fetchXml
leadGrid.control.setParameter("fetchXml", fetchXml);
//Force the subgrid to refresh
leadGrid.control.refresh();

}

CRM 2011 JS: Change Subgrid View JScript

// Change Subgrid View Java Script

 

Change the Fetch XML and set the subgrid ID

function UpdateSubGrid()

{

    var leadGrid = document.getElementById("Contact");//Set Subgrid ID 

  //If this method is called from the form OnLoad, make sure that the grid is loaded before proceeding

  if (leadGrid.readyState != "complete")

  {

      //The subgrid hasn't loaded, wait 1 second and then try again

      setTimeout('UpdateLeadSubGrid()', 1000);

      return;

  }

 

 

var fetchXml = "              ";//Set Fetch XML

  //Inject the new fetchXml

  leadGrid.control.setParameter("fetchXml", fetchXml);

  //Force the subgrid to refresh

  leadGrid.control.refresh();

 

}

CRM 2011 JS: Hide From Footer

function Hide_Footer()
{
  document.getElementById("crmFormFooter").parentElement.style.display = "none";
}

CRM 2011 JS: Hide From Footer

function Hide_Footer()

{

  document.getElementById("crmFormFooter").parentElement.style.display = "none";

}

 

CRM 2011 JS: Hide Ribbon

function Hide_Ribbon()

{

  setTimeout(function () { window.top.document.getElementById("minimizeribbon").fireEvent("onclick"); }, 0);

}

 

CRM 2011 JS: Hide Areas of a Form

// Toggle the Ribbon Toolbar to Show/Hide (same as clicking the show/hide Ribbon button)

window.top.document.getElementById("minimizeribbon").fireEvent("onclick");

 

// Hide the Ribbon Toolbar and move the form Content area to the top of the window.

window.top.document.getElementById("crmTopBar").style.display = "none";

window.top.document.getElementById("crmContentPanel").style.top = "0px";

// Move Form Content area up to top of window, initial style.top is 135px

 

// Hide Left Hand Nav bar / pane

document.getElementById("crmNavBar").parentElement.style.display = "none";

document.getElementById("tdAreas").parentElement.parentElement.parentElement.parentElement.colSpan = 2;

 

// Hide the Breadcrumb and Record Set Toolbar

document.getElementById("recordSetToolBar").parentElement.style.display = "none";

 

// Hide the Form Footer Bar

document.getElementById("crmFormFooter").parentElement.style.display = "none";

 

CRM 2011: Integrate Dynamics CRM 2011 with Sharepoint Foundation 2010

Once we have Sharepoint (either server or foundation) installed, we can then integrate it with crm 2011. Some things to keep in mind before we start:

1. Install the crm 2011 list component for sharepoint, if you want your documents in crm to look and feel like they belong in crm. Without it, sharepoint will show up like an iframe with url pointing to your document library.
http://www.microsoft.com/download/en/details.aspx?id=5283
2. You can have a single org point to multiple sharepoint sites. The corollary is true too: a single sharepoint site can be referenced by multiple orgs. This assumes the right user permissions.
3. You can enable document management for out of the box and custom entites.
4. A single entity (say account), can point to multiple folder locations in the same sharepoint site. For example, one location would have all the account invoices, another folder the account's orders, etc.

Here are the steps to do the integration:

1. Go to Settings/ Document Manager/ Document Manager Settings. Select the entities you want, and enter the sharepoint site url

 

2. If the sharepoint site url is a valid url, you can choose to create the folder structure, which can be based on contact or account entity. If you leave the option blank, folders are created in sharepoint for each entity at the same level




3. Document libraries are created in sharepoint




4. Once folders are created successfully, go to an account and select the documents navigation link on the left. Here you can either give the location of an existing folder, or have crm create a new one for you.

5. And voila! sharepoint, in all its glory, inside crm 2011!

 

CRM 2011 SSRS: CRM 2011 Online Reports with FetchXML

CRM 2011 has the ability to create custom reports in SSRS using FetchXML.

Before you start, you need to have BIDS installed. BIDS is available as part of SQL Server Install, and is not available free.
Secondly, install Microsoft Dynamics CRM 2011 Report Authoring Extension.


This is how to create reports in SSRS using FetchXML (CRM 2011).

Here are the steps:


1. Use advanced find to create a query that will be used by the report. Choose all the colums that you need in the report. Then select "Download FetchXML" button on the advanced find ribbon. Save the xml file.

 



2. Go to Settings/ Customizations/ Developer Resources and note down the Organization unique name

 

 

 3. Launch BIDS and create a new Report Server Project.



4. In Solution Explorer, right click on reports and select "Add New Report". Give a name for the data source, and select "Microsoft Dynamics CRM Fetch" as the Type. The connection string is in this format:
CRM online url;org_name;home realm url


Home Realm URL is the Identity Provider used by your organization and is needed when your organization uses Federation for identity management. For our setup, I am giving the server url and org name only.

Do not make it a shared data source!



5. Under credentials, provide your live id and password to log into crm online.



6. Create a new data set for the data source created. Select Query Type as "Text". You can now import the FetchXML that was saved in step 1 into the Query area. Choose the Query Designer, and execute the query to make sure you return results that are the same as from the advanced find.

If you want to parameterize the search, replace the value="3" (for last 3 months) with value="@months". Notice I have done the same for total cost.




7. Create the report. From the figure, you will see that I have grouped the report first by Account Name, and I have grouped it further by total revenue for each account and for the grand total.



8. Save the rdl. In crm Online, if you want the report to be part of a solution, go to settings/solution, open/ create a new solution, go to components/ reports and add the new report from file. Choose to display it in the reports section.


9. Run the report from Workplace/ Reports. For this report, I have selected all orders that have shipped in the last 4 months, and have revenue of more than 10,000$.

 

CRM 2011 JS: Filter lookup values using javascript and fetchXml

//Filter lookup values using javascript and fetchXml

 

// call function on picklist onchange and form onload event 
function filterLookup() {
    //get defaul view id
    var defaultViewId = Xrm.Page.getControl("pms_timesheetperiod").getDefaultView();
 
    var fiscalYear = Xrm.Page.getAttribute("pms_fiscalyear").getValue();
 
    if (fiscalYear != null) {

        // use randomly generated GUID Id for our new view
        var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}";
        var entityName = "pms_timesheetperiod";

        // give the custom view a name
        var viewDisplayName = "Active time sheet periods for " + fiscalYear + "";

        // find all contacts where [Parent Customer] = [Account indicated by AccountId]
        // AND where [Statecode] = Active
        var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                     "<entity name='pms_timesheetperiod'>" +
                     "<attribute name='pms_fiscalyear' />" +
                     "<attribute name='pms_name' />" +
                     "<filter type='and'>" +
                     "<condition attribute='pms_fiscalyear' operator='eq' value='" + fiscalYear + "' />" +
                     "</filter>" +
                     "</entity>" +
                     "</fetch>";
     
        // build Grid Layout
        var layoutXml = "<grid name='resultset' " +
                               "object='1' " +
                               "jump='pms_timesheetperiodid' " +
                               "select='1' " +
                               "icon='1' " +
                               "preview='1'>" +
                           "<row name='result' " +
                                "id='pms_timesheetperiodid'>" +
                             "<cell name='pms_fiscalyear' " +
                                   "width='200' />" +
                             "<cell name='pms_name' " +
                                   "width='250' />" +
                           "</row>" +
                         "</grid>";
     
        // add the Custom View to the indicated [lookupFieldName] Control
        Xrm.Page.getControl("pms_timesheetperiod").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
    }
    else {
        // set default view id
        Xrm.Page.getControl("pms_timesheetperiod").setDefaultView(defaultViewId);
    }

CRM 2011 JS: Dynamic Controls in CRM Form (Button) 1

// Add button in crm

function addButton(attributename) {

    if (document.getElementById(attributename) != null) {

        var sFieldID = "field" + attributename;

        var elementID = document.getElementById(attributename + "_d");

        var div = document.createElement("div");

        div.style.width = "19%";

        div.style.textAlign = "right";

        div.style.display = "inline";

        elementID.appendChild(div, elementID);

        div.innerHTML = '<button id="' + sFieldID + '"  type="button" style="margin-left: 4px; width: 100%;" ><img src="/_imgs/img.gif" border="0" alt="Dial this number"/></button>';

        document.getElementById(attributename).style.width = "80%";

        document.getElementById(sFieldID).onclick = function () {onbuttonclick(); };

    }

}

 

function onbuttonclick() {

    alert('Hi');

}

CRM 2011 Tool: Code Generation Tool (CrmSvcUtil.exe) Command Line

Examples to use the code generation utility from the command line for each deployment type

Claims Authentication Active Directory
CrmSvcUtil.exe /url:http://CRM2011:5555/Org/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:administrator /password:password


Microsoft Dynamics CRM Online
CrmSvcUtil.exe /url:https://org.crm.dynamics.com/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:"liveid@live.com" /password:"mypassword!" /deviceid:"9eqd9qip4meckbxhyi838gn3" /devicepassword:"543opae9itRWKO+U7fe+I3MRVANUyFFPcfDJYP5ItZo="


Claims Authentication - IFD
CrmSvcUtil.exe /url:https://org.crm.com:5555/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:administrator /password:password

CRM 2011 CS: Use the Early Bound Entity Classes for Create, Update, and Delete

// This is how to Use the Early Bound Entity Classes for Create, Update, and Delete in CRM 2011

Create a New Entity Record Using the Early-bound Entity Classes and the Organization Service Context
OrganizationServiceContext orgContext =new OrganizationServiceContext(_serviceProxy);
Contact contact = new Contact()
{
   FirstName = "xyz",
   LastName = "abc",
   Address1_Line1 = "1337",
   Address1_City = "London",
   Address1_StateOrProvince = " South Wales ",
   Address1_PostalCode = "000000",
   Telephone1 = "44-123-4567"
};
orgContext.AddObject(contact);
orgContext.SaveChanges();



Update a New Entity Record Using the Early-bound Entity Classes and the Organization Service Context
var contact =  orgContext .CreateQuery<Contact>().First(c => c.FirstName == "xyz");
contact.JobTitle = "xCRM Hack";
orgContext .UpdateObject(contact);
orgContext .SaveChanges();



Delete a New Entity Record Using the Early-bound Entity Classes and the Organization Service Context
var contact =  orgContext .CreateQuery<Contact>().First(c => c.FirstName == "xyz");
orgContext .DeleteObject(contact);
orgContext .SaveChanges();




Create a New Entity Record Using the Early-Bound Entity Classes and without a Context Object
Contact contact = new Contact()
{
   FirstName = "xyz",
   LastName = "abc",
   Address1_Line1 = "1337",
   Address1_City = "London",
   Address1_StateOrProvince = " South Wales ",
   Address1_PostalCode = "000000",
   Telephone1 = "44-123-4567"
};
_contactId = _serviceProxy.Create(contact);

 

CRM 2011 CS: Send an Email in CRM 2011

// Send an Email in CRM 2011

 

 

// Namespaces

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Sdk.Discovery;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Crm.Sdk.Messages;

 

 

 

//CODE:Send an Email in CRM 2011

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,

                                                    serverConfig.HomeRealmUri,

                                                    serverConfig.Credentials,

                                                    serverConfig.DeviceCredentials))

{

    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

 

    Guid _contactId = new Guid("67B45Cdf-C56F-456F-B145-1237435430E6");

 

    WhoAmIRequest systemUserRequest = new WhoAmIRequest();

    WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);

    Guid _userId = systemUserResponse.UserId;

 

    // Create the 'From:' activity party for the email

    ActivityParty fromParty = new ActivityParty

    {

        PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)

    };

 

    // Create the 'To:' activity party for the email

    ActivityParty toParty = new ActivityParty

    {

        PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)

    };

 

    // Create an e-mail message.

    Email email = new Email

    {

        To = new ActivityParty[] { toParty },

        From = new ActivityParty[] { fromParty },

        Subject = "e-mail",

        Description = "SendEmail Message.",

        DirectionCode = true

    };

    Guid _emailId = _serviceProxy.Create(email);

 

    // Use the SendEmail message to send an e-mail message.

    SendEmailRequest sendEmailreq = new SendEmailRequest

    {

        EmailId = _emailId,

        TrackingToken = "",

        IssueSend = true

    };

 

    SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);

}

 

CRM 2011 JS: Get and Set attribute value in CRM 2011

This is how to Get and Set attribute value using javascript in CRM 2011

Get Attribute Value
var name = Xrm.Page.getAttribute("attributename").getValue();

Set Attribute Value
Xrm.Page.getAttribute("attributename").setValue('Navish');

 

crm 2011 JS: Get and Set lookup value using javascript in CRM 2011

//This is how to Get and Set lookup value using javascript in CRM 2011  

Get a lookup value
var lookup = new Array();
lookup = Xrm.Page.getAttribute("attributename").getValue();
if (lookup != null) {
    var name = lookup[0].name;
    var id = lookup[0].id;
    var entityType = lookup[0].entityType;
}


Set a lookup value
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = recorid;
lookup[0].name = recordname;
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("attributename").setValue(lookup);


Alternate method to set lookup value
Xrm.Page.getAttribute("attributename").setValue([{ id: recorid, name: recordname, entityType: entityname}]);

 

CRM 2011 JS: Set attribute requirement level using javascript in CRM 2011

This is how to Set attribute requirement level using javascript in CRM 2011

 

Requirement level setting

Xrm.Page.getAttribute("attributename").setRequiredLevel("none");

Xrm.Page.getAttribute("attributename").setRequiredLevel("required");

Xrm.Page.getAttribute("attributename").setRequiredLevel("recommended");

 

CRM 2011 JS: Get OptionSet attribute value and text in CRM 2011

//This is how to Get OptionSet attribute value and text  in CRM 2011

var optionset = Xrm.Page.getAttribute("attributename");

Get Optionset Text
var text = optionset.getText();

Get Optionset Value
var value = optionset.getValue();

 

CRM 2011 JS: Get the label name of the attribute in CRM 2011

// This is how to Get the label name of the attribute  in CRM 2011

 

//Get attribute label name

var label = Xrm.Page.getControl("atrributename").getLabel();

 

CRM 2011 JS: Get the current entity name using javascript in CRM 2011

// This is how to Get the current entity name using javascript in CRM 2011

 

// Get current entity name

var entity = Xrm.Page.data.entity.getEntityName();

 

CRM 2011 JS: Check modified Form using javascript in CRM 2011

// This is how to check , form is modified or not using getIsDirty() function.

// This function will return True in case of form is modified

 

// Get modified form

var ismodified = Xrm.Page.data.entity.getIsDirty();

CRM 2011 JS: Get Organization Name using javascript in CRM 2011

// This is how to Get Organization Name using javascript in CRM 2011

 

// Get current organization name

var orgName = Xrm.Page.context.getOrgUniqueName();

CRM 2011 JS: Get Server URL using javascript in CRM 2011

// This is how to Get Server URL using javascript in CRM 2011

 

// Get server URL

var serverURL = Xrm.Page.context.getServerUrl();

CRM 2011 JS: Get Current record ID in CRM 2011

//This is how to Get Current record ID using javascript in CRM 2011.

 

//Get current record id

var Id = Xrm.Page.data.entity.getId();

CRM 2011 JS: Get and Set control disabled in CRM 2011

This is how to Get and Set control disabled  in CRM 2011

 

Get disable control

var isdisable = Xrm.Page.ui.controls.get("attributename").getDisabled();

True value shows disable field

 

Set control disable

Xrm.Page.ui.controls.get("attributename").setDisabled(true);

CRM 2011 JS: Get Form type using javascript in CRM 2011

//This is how to Get Form type in CRM 2011

 

Get from type

var type = Xrm.Page.ui.getFormType();

 

getFromType() function returns integer value for different Form states

0 - undefined

1 - Create

2 - Update

3 - Read Only

4 - Disabled

5 - Quick Create (Deprecated)

6 - Bulk Edit

 

CRM 2011 JS: Save and Close function for CRM 2011

//This is how to Save and Close function in javascript for CRM 2011

 

//Save function

Xrm.Page.data.entity.save();

 

//Save and Close function

Xrm.Page.data.entity.save("saveandclose");

 

//Save and New function

Xrm.Page.data.entity.save("saveandnew");

 

//Close function

Xrm.Page.ui.close();

CRM 2011 JS: Set focus on control using javascript in CRM 2011

This is how to Set focus on control using javascript in CRM 2011

 

 

// Set focus on control

Xrm.Page.ui.controls.get("attributename").setFocus();

CRM 2011 JS: Hide a attribute on form using javascript in CRM 2011

This is how to Hide a attribute on form using javascript in CRM 2011

 

//Hide a attribute

Xrm.Page.ui.controls.get("attributename").setVisible(false);

CRM 2011 JS: Get Current user id

//This is how to get Get Current user id using javascript in CRM 2011

 

 

//Get Current user id

var userID = Xrm.Page.context.getUserId();

CRM 2011 JS: Attach event to attribute using javascript in CRM 2011

//This is how to Attach event to attribute using javascript in CRM 2011

Attach event to attribute

crmForm.all.new_isdue.attachEvent("onclick", Onisdueclick);
function  Onisdueclick () {
    alert('Hi');
}

 

CRM 2011 JS: Refresh ribbon

//This is how to refresh current entity ribbon

Refresh ribbon
Xrm.Page.ui.refreshRibbon()

 

CRM 2011 JS: Retrieve form all controls

//This is how to Retrieve form all controls using javascript in CRM 2011

//Retrieve all controls
Xrm.Page.ui.controls.forEach(function (control, index) {
    var attribute = control.getAttribute();
    if (attribute != null) {
        var attributeName = attribute.getName();
    }
});

 

CRM 2011 JS: Insert FetchXml into subgrid chart's view

// CRM 2011 JS: Insert FetchXml into subgrid chart's view

 

function UpdateSubGrid() {

var accountSales = document.getElementById("SalesSummary");

if (accountSales.readyState != "complete") {

  setTimeout('UpdateSubGrid()', 1000);

  return;

}

 

var accID = Xrm.Page.data.entity.getId();

alert(accID);

 

var accountNum = Xrm.Page.getAttribute("jensen_accountnumber").getValue();

 

var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>";

  fetchXml += " <entity name='account'>";

  fetchXml +=  " <attribute name='jensen_yeartodatesales' />";

  fetchXml +=  " <attribute name='jensen_yeartodateplan' />";

  fetchXml +=  " <attribute name='jensen_lastyearsales' />";

  fetchXml +=  " <attribute name='name' />";

  fetchXml +=  " <filter type='and'>";

  fetchXml +=  " <condition attribute='statecode' operator='eq' value='0' />";

  fetchXml +=  " <condition attribute='accountnumber' operator='eq' value='";

  fetchXml +=  accountNum;

  fetchXml +=  "' />";

  fetchXml +=  " </filter>";

  fetchXml +=  " <order attribute='name' descending='false' />";

  fetchXml +=  " </entity></fetch>";

alert(fetchXml);

 

accountSales.control.setParameter("fetchXml", fetchXml);

 

accountSales.control.refresh();

}

CRM 2011 JS: Get current user roles

This is how to get current user roles

Current user roles
var UserRoles = Xrm.Page.context.getUserRoles();

 

CRM 2011 JS: Get data in fields that have changed on form using

This is how to get only changed data

Get changed data 
Xrm.Page.data.entity.getDataXml()

 

CRM 2011 JS: Hide and Show tab

This is how to hide and show tab

Hiding tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(false);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(false);


Showing tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(true);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(true);

 

CRM 2011 JS: SOAP Request Example for new_entityname

/*

The following is the SOAP Request Example for new_entityname

*/

 

function SOAPReqbyExample() {

    var GUIDvalue = Xrm.Page.data.entity.getId();

    //var name = Xrm.Page.getattrib(

 

    if (GUIDvalue != null) {

 

        var varh = GUIDvalue;

    }

 

    var authenticationHeader = GenerateAuthenticationHeader();

 

    // Prepare the SOAP message.

    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'>" +

authenticationHeader +

"<soap:Body>" +

"<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +

"<entity xsi:type='new_entityname'>" +

"<new_fieldname>" + varh + "</new_fieldname>" +

"</entity>" +

"</Create>" +

"</soap:Body>" +

"</soap:Envelope>";

    // Prepare the xmlHttpObject and send the request.

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

    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);

    xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Create");

    xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

    xHReq.setRequestHeader("Content-Length", xml.length);

    xHReq.send(xml);

    alert("Created");

    // Capture the result

    var resultXml = xHReq.responseXML;

 

    // Check for errors.

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

    if (errorCount != 0) {

        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;

        alert(msg);

    }

 

}

 

CRM 2011 JS: Hide and Show section using javascript in CRM 2011

// Hide and Show section using javascript in CRM 2011

// Hiding Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(false);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(false);

// Showing Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(true);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(true);

 

CRM 2011 JS: Expand / Collapse tab using javascript in CRM 2011

// Expand / Collapse tab example

// Expand tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('expanded');

//Collapse tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('collapsed');

 

CRM 2011 JS: Open popup window using javascript in CRM 2011

This is how to open popup window

//CRM function to open a Popup window
var url = "http://crm2011:5555/test/main.aspx?etn=account&pagetype=entityrecord";
var name = "popup";
var width = 800;
var height = 600;
var feature = "status=1";
openStdWin(url, name, width, height, feature);

 

CRM 2011 JS: Soap XML Retrieve using javascript in CRM 2011

Soap XML Retrieve using javascript in CRM 2011

Use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/Retrieve

This javascript code is fetching Account entity address into using  Contact parentcustomerid attribute and filling in Contact address fields


Soap XML retrieve

if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null) {
    //acount guid no
    var parentcustomerID = Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].id;
    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>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>account</entityName>" +
    "<id>" + parentcustomerID + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
        "<q1:Attributes>" +
            "<q1:Attribute>address1_addresstypecode</q1:Attribute>" +
            "<q1:Attribute>address1_name</q1:Attribute>" +
            "<q1:Attribute>address1_line1</q1:Attribute>" +
            "<q1:Attribute>address1_line2</q1:Attribute>" +
            "<q1:Attribute>address1_city</q1:Attribute>" +
            "<q1:Attribute>address1_stateorprovince</q1:Attribute>" +
            "<q1:Attribute>address1_postalcode</q1:Attribute>" +
            "<q1:Attribute>address1_country</q1:Attribute>" +
            "<q1:Attribute>address1_telephone1</q1:Attribute>" +
        "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_addresstypecode") != null) { Xrm.Page.getAttribute("address1_addresstypecode").setValue(resultXml.selectSingleNode("//q1:address1_addresstypecode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_addresstypecode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_name") != null) {
Xrm.Page.getAttribute("address1_name").setValue(resultXml.selectSingleNode("//q1:address1_name").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_name").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line1") != null) {
Xrm.Page.getAttribute("address1_line1").setValue(resultXml.selectSingleNode("//q1:address1_line1").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line1").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line2") != null) {
Xrm.Page.getAttribute("address1_line2").setValue(resultXml.selectSingleNode("//q1:address1_line2").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line2").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {
Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {
Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_postalcode") != null) {
Xrm.Page.getAttribute("address1_postalcode").setValue(resultXml.selectSingleNode("//q1:address1_postalcode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_postalcode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_country") != null) {
Xrm.Page.getAttribute("address1_country").setValue(resultXml.selectSingleNode("//q1:address1_country").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_country").setValue(null);
    }
}

 

CRM 2011 JS: Soap XML RetrieveMultiple using javascript

Use Soap XML Retrieve web service
This javascript code is fetching all contact have same value as custom attribute value


Soap XML retrievemutliple
var contactname = Xrm.Page.getAttribute("new_contact").getValue();
var authenticationHeader = GenerateAuthenticationHeader();
if (contactname != null && contactname != "undefined") {
    var Accountxml = "" + "<?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\">" +
    authenticationHeader +
    "  <soap:Body>" +
    "    <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "      <query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:QueryExpression\'>" +
    "        <q1:EntityName>contact</q1:EntityName>" +

    "        <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    "          <q1:Attributes>" +
    "            <q1:Attribute>address1_city</q1:Attribute>" +
    "            <q1:Attribute>address1_stateorprovince</q1:Attribute>" +
    "          </q1:Attributes>" +
    "        </q1:ColumnSet>" +

    "        <q1:Distinct>false</q1:Distinct>" +

    "        <q1:PageInfo>" +
    "          <q1:PageNumber>1</q1:PageNumber>" +
    "          <q1:Count>1</q1:Count>" +
    "        </q1:PageInfo>" +

    "        <q1:Criteria>" +
    "          <q1:FilterOperator>And</q1:FilterOperator>" +
    "          <q1:Conditions>" +
    "            <q1:Condition>" +
    "              <q1:AttributeName>firstname</q1:AttributeName>" +
    "              <q1:Operator>Equal</q1:Operator>" +
    "              <q1:Values>" +
    "                <q1:Value xsi:type=\"xsd:string\">" + contactname + "</q1:Value>" +
    "              </q1:Values>" +
    "            </q1:Condition>" +
    "          </q1:Conditions>" +
    "        </q1:Criteria>" +
    "      </query>" +
    "    </RetrieveMultiple>" +
    "  </soap:Body>" +
    "</soap:Envelope>" +
    "";
    // Create an instance of an XMLHTTP object.
    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", Accountxml.length
            );

    // Send the XMLHttp request.
    xmlHttpRequest.send(Accountxml);
    // Capture the XMLHttp response in XML format.
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {         Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }


    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {         Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

}

CRM 2011 CS: Retrieve the schedule of a system user

/* Retrive The Schedule of Current User */

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,

                                                    serverConfig.HomeRealmUri,

                                                    serverConfig.Credentials,

                                                    serverConfig.DeviceCredentials))

{

    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

 

                  

    // Get the current user's information.

    WhoAmIRequest userRequest = new WhoAmIRequest();

    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

 

    // Retrieve the schedule of the current user.                                           

    QueryScheduleRequest scheduleRequest = new QueryScheduleRequest

    {

        ResourceId = userResponse.UserId,

        Start = DateTime.Now,

        End = DateTime.Today.AddDays(7),

        TimeCodes = new TimeCode[] { TimeCode.Available }

    };

    QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)_serviceProxy.Execute(scheduleRequest);

}