Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Tuesday, 25 June 2013

CRM 2011 Query Expression samples

Query Expression Sample 1

// Create the ConditionExpression.
ConditionExpression condition1 = new ConditionExpression("contractid", ConditionOperator.Equal, entityId);

 // Create the FilterExpression.
 FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
 filter.FilterOperator = LogicalOperator.And;
 filter.Conditions.Add(condition1);

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = "contractdetail";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;

//Build Retrieve request
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
             
//Retrieve SLARuleTemplates
RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(retrieve);


Query Expression Sample(Link Entity) 2

//Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
QueryExpression qe = new QueryExpression();
qe.EntityName = "account";
qe.ColumnSet = new ColumnSet();
qe.ColumnSet.Columns.Add("name");

qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner));
qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname");
qe.LinkEntities[0].EntityAlias = "primarycontact";

EntityCollection ec = _orgService.RetrieveMultiple(qe);


Query Expression Sample( One-To-Many Relationship)

// Construct query
// Condition where task attribute equals account id.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "regardingobjectid";
condition.Operator = ConditionOperator.Equal;
condition.Values.Add(acctId.ToString());

//Create a column set.
ColumnSet columns = new ColumnSet("subject");

// Create query expression.
QueryExpression query1 = new QueryExpression();
query1.ColumnSet = columns;
query1.EntityName = "task";
query1.Criteria.AddCondition(condition);

EntityCollection result1 = _serviceProxy.RetrieveMultiple(query1);

Page Large Result Sets with Query Expression

//  Query using the paging cookie.
// Define the paging attributes.
// The number of records per page to retrieve.
int fetchCount = 3;
// Initialize the page number.
int pageNumber = 1;
// Initialize the number of records.
int recordCount = 0;

// Define the condition expression for retrieving records.
ConditionExpression pagecondition = new ConditionExpression();
pagecondition.AttributeName = "address1_stateorprovince";
pagecondition.Operator = ConditionOperator.Equal;
pagecondition.Values.Add("WA");

// Define the order expression to retrieve the records.
OrderExpression order = new OrderExpression();
order.AttributeName = "name";
order.OrderType = OrderType.Ascending;

// Create the query expression and add condition.
QueryExpression pagequery = new QueryExpression();
pagequery.EntityName = "account";
pagequery.Criteria.AddCondition(pagecondition);
pagequery.Orders.Add(order);
pagequery.ColumnSet.AddColumns("name", "address1_stateorprovince", "emailaddress1", "accountid");

// Assign the pageinfo properties to the query expression.
pagequery.PageInfo = new PagingInfo();
pagequery.PageInfo.Count = fetchCount;
pagequery.PageInfo.PageNumber = pageNumber;
// The current paging cookie. When retrieving the first page,
// pagingCookie should be null.
pagequery.PageInfo.PagingCookie = null;

Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

  while (true)
  {
    // Retrieve the page.
     EntityCollection results = _serviceProxy.RetrieveMultiple(pagequery);

     if (results.Entities != null)
     {
        // Retrieve all records from the result set.
         foreach (Account acct in results.Entities)
         {
           Console.WriteLine("{0}.\t{1}\t\t{2}",++recordCount,acct.EMailAddress1,                       
           acct.Name);
         }
    }

    // Check for more records, if it returns true.
    if (results.MoreRecords)
    {
       // Increment the page number to retrieve the next page.
       pagequery.PageInfo.PageNumber++;
       // Set the paging cookie to the paging cookie returned from current results.
       pagequery.PageInfo.PagingCookie = results.PagingCookie;
    }
    else
    {
       // If no more records are in the result nodes, exit the loop.
       break;
    }
 }

Multiple condition with Query Expression.


// Create the ConditionExpression.
ConditionExpression condition1 = new ConditionExpression("new_contractserviceid", ConditionOperator.Equal, contractserviceid);
ConditionExpression condition2 = new ConditionExpression("new_componenttemplateid", ConditionOperator.Equal, componentTemplate.Get(executionContext).Id);

// Create the FilterExpression.
FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
filter.Conditions.Add(condition2);

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = "new_component";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;

//Build Retrieve request
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
          
//Retrieve SLARuleTemplates
RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(retrieve);






Friday, 3 May 2013


Understanding Plug-ins in MS CRM 2011

A plug-in is custom business logic (code) that you can integrate with Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online to modify or augment the standard behavior of the platform. Another way to think about plug-ins is that they are handlers for events fired by the Microsoft Dynamics CRM platform. You can subscribe, also known as registering, a plug-in to a known set of events to have your code run when the event occurs.

Plug-in will be part of Transactions and will trace the exception during execution.


• PreEvent  : Stage 10: Pre-validation

• PreEvent  : Stage 20: Pre-operation

• Core Operation : Stage 30: MainOperation

• PostEvent   : Stage 40: Post-operation

• PostEvent   : Stage 50: Post-operation (deprecated*)

Stage 20,30,40 are Transaction Scope.


Sync/Async Execution

Plugins can execute in
- Synchronously during pipeline execution

- Asynchronously – queued for later execution


Transaction Support

CRM 2011 Stages support plugin execution inside the database transaction
- Stages 20 & 40

Uncaught exceptions force a rollback
IExecutionContext.IsInTransaction
Transaction spans CRM DB operations only
- No distributed transaction support

Plugins registered outside transaction stage will participate in transaction if executed as nested pipeline of transactional parent.



Saturday, 27 April 2013

CRM 2011 Basic Javacript Syntax



Set the value of a CRM field
Xrm.Page.getAttribute(“CRMFieldName“).setValue(“New Value”);


Get the value from a CRM field
var value = Xrm.Page.getAttribute(“CRMFieldName”).getValue();

Get the value from a CRM OptionSet field
var value = Xrm.Page.getAttribute(“CRMFieldName”).getValue();

Get the text from a CRM OptionSet field
var text = Xrm.Page.getAttribute(“CRMFieldName”).getText();

Set the value of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMFieldName”).setValue(“1″); // OptionSet Value

Get the selected text of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMFieldName”).getSelectedOption().text;

Get the selected value of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMFieldName”).getSelectedOption().value;

Get the text and value of a CRM Lookup 
var lookupObject = Xrm.Page.getAttribute(“CRMLookupName”).getValue();
lookupObject[0].name; 
lookupObject[0].id;

Set the value of a CRM Lookup field
var lookup = new Array();
var Item= new Object();
Item.id = "Guid Value"
Item.name = “Contact”; // Entity name
Item.entityType = “EntityName”;
lookup [0] = Item;
Xrm.Page.getAttribute(“CRMLookupName”).setValue(lookupData);

Disable CRM field
Xrm.Page.ui.controls.get(“CRMFieldName”).setDisabled(true);

Hide CRM field
Xrm.Page.ui.controls.get(“CRMFieldSchemaName”).setVisible(false);

Hide a Tab in CRM
Xrm.Page.ui.tabs.get(“tabName”).setVisible(false);

Hide a Section in CRM
var tab = Xrm.Page.ui.tabs.get(“tabName”);
tab.sections.get(“sectionName”).setVisible(false);

Set the Requirement level in CRM
Xrm.Page.getAttribute(“CRMFieldName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“CRMFieldName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“CRMFieldName”).setRequiredLevel(“recommended”);

Set Focus on a field in CRM
Xrm.Page.ui.controls.get(“CRMFieldName”).setFocus(true);

Cancelling Onsave Event in CRM
event.returnValue = false;
return false;

Check IsDirty in CRM field
var isDirty = Xrm.Page.getAttribute(“CRMFieldName”).getIsDirty();
alert(isDirty); // returns true if the field is dirty

Check IsDirty for all the fields in CRM
var isDirty = Xrm.Page.data.entity.getIsDirty();
alert(isDirty); // returns true if any of the field is dirty in the entire form.

Force Submit a read only field in CRM
Xrm.Page.getAttribute(“CRMFieldName”).setSubmitMode(“always”);

Preventing an attribute to be saved in CRM form
Xrm.Page.getAttribute(“CRMFieldName”).setSubmitMode(“never”);

Get Unique Organization Name in CRM
Xrm.Page.context.getOrgUniqueName();

Get Server url in CRM
Xrm.Page.context.getServerUrl();

Get the record Id in CRM
Xrm.Page.data.entity.getId();

Get the User Id in CRM
Xrm.Page.context.getUserId();

Get the Entity Schema Name in CRM
Xrm.Page.data.entity.getEntityName();

Get the UserRole Id’s in CRM
var userRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < userRoles.length; i++)
{
var userRole = userRoles[i]; // returns the Role Id
}

Get the Form Type in CRM
Xrm.Page.ui.getFormType();

Save a record in CRM
Xrm.Page.data.entity.save(); // for saving a record
Xrm.Page.data.entity.save(“saveandclose”); // for save and close
Xrm.Page.data.entity.save(“saveandnew”); // for save and new

Close the form in CRM
Xrm.Page.ui.close();

Retrieve Entity using FetchXML in CRM 2011 Java Script


var pricelistlookup = null;
var accountname = null;

FetchPriceList = function (pricelistfield) {
    pricelistlookup = pricelistfield;

    if (Xrm.Page.getAttribute(pricelistlookup).getValue() == null) {
        var _oService;
        var _sServerUrl = Xrm.Page.context.getServerUrl();

        var fetchXml =
         "<fetch mapping=\"logical\">" +
                "<entity name=\"pricelevel\">" +
                    "<attribute name=\"name\" />" +
                    "<attribute name=\"pricelevelid\" />" +
                    "<filter>" +
                        "<condition attribute=\"statecode\" operator=\"eq\" value=\"" + "0" + "\" />" +
                         "<condition attribute='name' operator='eq' value='Default Price List' />" +
                    "</filter>" +
                "</entity>" +
            "</fetch>";

        _oService = new FetchUtil(_sServerUrl);
        _oService.Fetch(fetchXml, FetchPriceListCallBack);
    }
}

FetchPriceListCallBack = function (results) {
    try {
        if (results.length > 0) {
            var lookupData = new Array();
            var lookupItem = new Object();

            // Set the id, typename, and name properties to the object.
            lookupItem.id = results[0].attributes.pricelevelid.value;
            lookupItem.entityType = 'pricelevel';
            lookupItem.name = results[0].attributes.name.value;
            lookupData[0] = lookupItem;
            Xrm.Page.getAttribute(pricelistlookup).setValue(lookupData);
        }
    }
    catch (e) { alert("Default Price List Not found!!!"); }

}

Retrieve entity using ODATA in CRM 2011 Javascript

Retrieve a entity data using ODATA in CRM 2011 javascript


function retrieveSelectedProduct(productid) {
    var entity = "Product";    //Entity name
    var select = "?$select=ProductId,DefaultUoMId,ProductNumber"  // Columns Name
    var oDataSelect;
   var context = Xrm.Page.context;
   var serverUrl = context.getServerUrl();

    // build query string
    oDataSelect = "/XRMServices/2011/OrganizationData.svc/" + entity + "Set(guid'" + productid + "')" + select + "";

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + oDataSelect,
        beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
        success: function (data, textStatus, XmlHttpRequest) {
            // Use for a single selected entity
            ProcessReturnMsg(data.d);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
        }
    });
}

function ProcessReturnMsg(productEntity) {
    if (productEntity.DefaultUoMId != null) {
        var uomId = productEntity.DefaultUoMId.Id;
        var uomName = productEntity.DefaultUoMId.Name;

        // insert the default unit of measure
        var defaultuomid = new Array();
        defaultuomid[0] = new Object();
        defaultuomid[0].id = uomId;
        defaultuomid[0].name = uomName;
        defaultuomid[0].entityType = "uom";

        Xrm.Page.getAttribute("uomid").setValue(defaultuomid);
    }
}