Thursday, September 27, 2012

Crm 2011 -Plugin tips

InputParameters["Target"]

Target is the entity record that the plugin is executed against. 
It is late bound, but you can use ToEntity() to convert it into early bound instance
One thing useful to know about this instance is that it only contains “dirty” attributes. 
Unchanged fields will simply not be there, if you converted to early bound, the value of the attribute will be null.

Sample code (without using developer toolkit)

  public void Execute(IServiceProvider serviceProvider)
        {
             IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

OrganizationServiceContext orgContext = new OrganizationServiceContext(service);


            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
            }
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

                Entity entity = (Entity)context.InputParameters["Target"];
              
                try
                {
                    //Do your custom logic here
                }
                catch (Exception Ex)
                {
                    throw new InvalidPluginExecutionException(Ex.Message);
                }
            }


            //throw new NotImplementedException();
        } 

 Sample code(using Developer Toolkit)

 protected void ExecutePreValidateAccountCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
          
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            var orgServiceContext = new OrganizationServiceContext(service);

            if (context.InputParameters.Contains("Target") &&
                             context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parmameters.
                Entity entity = (Entity)context.InputParameters["Target"];
               var newAccount = entity.ToEntity<Account>();
               
                try
                {
                  
                }
                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                }
            }

            // TODO: Implement your custom Plug-in business logic.
        }


References
  http://sliong.wordpress.com/2012/06/06/crm-2011-event-execution-pipeline-and-target-input-parameters/

Tuesday, September 25, 2012

CRM 2011 - Get business unit using whoami request in XrmServiceToolkit

function GetBusinessUnit() {
var currentstore=Xrm.Page.getAttribute('jmh_store').getValue();
  if(currentstore == null)
{
    var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
    var resultXml = XrmServiceToolkit.Soap.Execute(request);
    var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
    var cols = ["name"];
    var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
    var buName = retrievedContact.attributes['name'].value;
    SetLookupValue('jmh_store', buid, buName, 'businessunit');
  }

function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}
}

Note : Add XrmServiceToolkit in the page library
Reference: http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions

Tuesday, September 18, 2012

CRM 2011 - javascript to retrieve data from lookup entity and map fields

function getcontactdetails() {
    var EntityName, EntityId,LookupFieldObject;
    var Name = "";      
    var resultXml;
    LookupFieldObject = Xrm.Page.data.entity.attributes.get('jmh_customer');
    if (LookupFieldObject.getValue() != null) {
        EntityId = LookupFieldObject.getValue()[0].id;
        EntityName = LookupFieldObject.getValue()[0].entityType;
        resultXml = RetrieveEntityById(EntityName, EntityId, 'jmh_title,fullname,address1_line1');
        if (resultXml != null && resultXml.selectSingleNode('//q1:jmh_title') != null) {
            Name = Name + resultXml.selectSingleNode('//q1:jmh_title').nodeTypedValue;
       }
       if (resultXml != null && resultXml.selectSingleNode('//q1:fullname') != null) {
           Name = Name +" "+ resultXml.selectSingleNode('//q1:fullname').nodeTypedValue;
       }
       if (resultXml != null && resultXml.selectSingleNode('//q1:address1_line1') != null) {
           Xrm.Page.data.entity.attributes.get('jmh_addressline1').setValue(resultXml.selectSingleNode('//q1:address1_line1').nodeTypedValue);
       }

}


//Do not make any changes
function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;
    arrayEntityColumns = prmEntityColumns.split(",");
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
    //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>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";
    //call function to create Soap Request to ms crm webservice
    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);
    resultXml = xmlHttpRequest.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}

Thanks to
Athul MT

Reference :
http://worldofdynamics.blogspot.in/2011/06/microsoft-dynamics-crm-2011-retrieve.html

Note:
to set lookup field
  if (resultXml != null && resultXml.selectSingleNode('//q1:defaultuomid') != null) {
         var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = resultXml.selectSingleNode('//q1:defaultuomid').nodeTypedValue;
            lookupValue[0].name = resultXml.selectSingleNode('//q1:defaultuomid').getAttribute("name");
             lookupValue[0].entityType =  resultXml.selectSingleNode('//q1:
defaultuomid').getAttribute("type");

            Xrm.Page.data.entity.attributes.get('uomid').setValue(lookupValue);
        }

Crm 2011 - Hiding navigation item based on two option(bit) value

function hideGunTransactionEntries()
{
        
        var isLockedfield=Xrm.Page.data.entity.attributes.get("jmh_lockedbypolice");
if(isLockedfield != null)
{
        var isLockedfieldValue=isLockedfield.getValue();

if(isLockedfieldValue == 1)
{

    var objNavItem = Xrm.Page.ui.navigation.items.get("nav_jmh_jmh_gun_jmh_guntransactionentry_gun");
    objNavItem.setVisible(false);

}
else
{

    var objNavItem = Xrm.Page.ui.navigation.items.get("nav_jmh_jmh_gun_jmh_guntransactionentry_gun");
    objNavItem.setVisible(true);

}
}
}

Wednesday, September 12, 2012

CRM 2011-javascript to make another field empty between two fields

function MakeEmpty(field1,field2)
{
var firstfield=Xrm.Page.data.entity.attributes.get(field1);
if(firstfield!=null)
{
var firstfieldvalue=firstfield.getValue();
if(firstfieldvalue!=null)
{
var secondfield=Xrm.Page.data.entity.attributes.get(field2);
if(secondfield!=null)
{
var secondfieldvalue=secondfield.setValue(null);
}
}
}
}

Note : call this method onchange event of  the two fields but  pass the field names as comma separated parameter
Field1-Current Field
Field2-Field to be empty

CRM 2011-Javascript to disable a field except create form

function DisableFieldAfterCreation(fieldName)
{
var formType = Xrm.Page.ui.getFormType();
if(formType != 1)
{
var field=Xrm.Page.ui.controls.get(fieldName);
if(field != null)
{
field.setDisabled(true);
}
}
}

Note: call this method onload of form and pass field name as parameter

Tuesday, September 11, 2012

CRM 2011-Javascript to multiple two fields

function CalculateLineCost()
{
var quantity=Xrm.Page.getAttribute("jmh_quantity").getValue();
var unitcost=Xrm.Page.getAttribute("jmh_unitcost").getValue();
if(quantity != null && unitcost)
{
var linecost=quantity*unitcost;
Xrm.Page.getAttribute("jmh_linecost").setValue(linecost);
}
}

Note:call this javascript on both two fields on change event

Saturday, September 8, 2012

CRM 2011 - javascript to compare with today datetime

function VerifyIssueDate()
{

var today=new Date();
var issueDate=Xrm.Page.data.entity.attributes.get("jmh_issuedate");

if(issueDate != null && issueDate.getValue() != null )
{
issueDateValue=issueDate.getValue();
if(issueDateValue.getFullYear() >  today.getFullYear())
{
alert("Issue Date must be on or before today");
issueDate.setValue(null);
}
else if (issueDateValue.getMonth() > today.getMonth() )
{
alert("Issue Date must be on or before today");
issueDate.setValue(null);
}
else if (issueDateValue.getDate() >  today.getDate() )
{
alert("Issue Date must be on or before today");
issueDate.setValue(null);
}
}
}


function VerifyExpiryDate()
{
var today=new Date();
var expiryDate=Xrm.Page.data.entity.attributes.get("jmh_expirydate");

if(expiryDate != null && expiryDate.getValue() != null)
{
var expiryDateValue= expiryDate.getValue();


if(expiryDateValue.getFullYear() <  today.getFullYear())
{
alert("Expiry Date must be on or after today");
expiryDate.setValue(null);
}
else if (expiryDateValue.getMonth() < today.getMonth() )
{
alert("Expiry Date must be on or after today");
expiryDate.setValue(null);
}
else if (expiryDateValue.getDate() <  today.getDate() )
{
alert("Expiry Date must be on or after today");
expiryDate.setValue(null);
}


}
}

Wednesday, September 5, 2012

crm 2011 -plugin to convert an entity and related entities

protected void ExecutePostRequisitionUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

             IPluginExecutionContext context = localContext.PluginExecutionContext;
             IOrganizationService service = localContext.OrganizationService;
   


    // The InputParameters collection contains all the data passed in the message request.
             if (context.InputParameters.Contains("Target") &&
             context.InputParameters["Target"] is Entity)
             {
                 // Obtain the target entity from the input parmameters.
                 Entity entity = (Entity)context.InputParameters["Target"];
                 ColumnSet cols = new ColumnSet(true);

                 var requisitionObj = service.Retrieve(jmh_requisition.EntityLogicalName, entity.Id, cols);
                 jmh_requisition currentRequisition = (jmh_requisition)requisitionObj;
                 if (entity.Attributes.Contains("statuscode"))
                 {
                     OptionSetValue val = (OptionSetValue)entity["statuscode"];
                     if (val.Value == 170000002)
                     {
                         var requisition = currentRequisition;
                      
                         var newPurchseOrder = new jmh_purchaseorder();
                         newPurchseOrder.jmh_supplier = requisition.jmh_supplier;
                         newPurchseOrder.new_Items = requisition.jmh_item;
                         newPurchseOrder.jmh_itemscost = requisition.jmh_itemcost;
                         newPurchseOrder.jmh_totalcost = requisition.jmh_totalcost;
                         newPurchseOrder.jmh_store = requisition.jmh_storeid;
                         EntityReference currentReq = new EntityReference();
                         currentReq.Id = requisition.Id;
                         currentReq.LogicalName = jmh_requisition.EntityLogicalName;
                         newPurchseOrder.jmh_requisition = currentReq;
                         var newPoId = service.Create(newPurchseOrder);
                         var query = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
<entity name='jmh_requisitionproduct'>
<attribute name='jmh_requisitionproductid'/>
<attribute name='jmh_existingproduct'/>
<attribute name='jmh_producttype'/>

<attribute name='jmh_unitcost'/>
<attribute name='jmh_quantity'/>
<attribute name='jmh_linecost'/>

<attribute name='jmh_name'/>
<attribute name='createdon'/>
<order descending='false' attribute='jmh_name'/>
<filter type='and'>
<condition attribute='jmh_requisition' value='" + currentRequisition.Id.ToString() + @"' uiname='" + currentRequisition.jmh_name
                                                         + @"' uitype='jmh_requisition'  operator='eq'/> </filter>
</entity>
 </fetch>";
                       

                         RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                         req.Query = new FetchExpression(query);
                         RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(req);
                         EntityCollection roProducts = response.EntityCollection;
                         foreach (var roProduct in roProducts.Entities)
                         {
                             var newPOproduct = new jmh_purchaseorderproduct();
                          

                             newPOproduct.jmh_ProductType = (bool)roProduct["jmh_producttype"];
                             EntityReference createdPo = new EntityReference();
                             createdPo.Id = newPoId;
                             createdPo.LogicalName = jmh_purchaseorder.EntityLogicalName;
                             newPOproduct.jmh_purchaseorder = createdPo;

                             if (roProduct.Attributes.ContainsKey("jmh_existingproduct") && roProduct["jmh_existingproduct"] != null)
                             {
                                 newPOproduct.jmh_existingproduct = (EntityReference)roProduct["jmh_existingproduct"];
                             }
                             if (roProduct["jmh_name"] != null && roProduct.Attributes.ContainsKey("jmh_name"))
                             {
                                 newPOproduct.jmh_writeinproduct = roProduct["jmh_name"].ToString();
                             }
                             if (roProduct["jmh_linecost"] != null && roProduct.Attributes.ContainsKey("jmh_linecost"))
                             {
                                 newPOproduct.jmh_linecost = (Money)roProduct["jmh_linecost"];
                             }

                             if (roProduct["jmh_quantity"] != null && roProduct.Attributes.ContainsKey("jmh_quantity"))
                             {
                                 newPOproduct.jmh_quantity = Convert.ToInt32(roProduct["jmh_quantity"]);
                             }
                             if (roProduct["jmh_unitcost"] != null && roProduct.Attributes.ContainsKey("jmh_unitcost"))
                             {
                                 newPOproduct.jmh_unitcost = (Money)roProduct["jmh_unitcost"];
                             }
                             service.Create(newPOproduct);
                         }
                     }
                 }
             }   
            // TODO: Implement your custom Plug-in business logic.
        }

Tuesday, September 4, 2012

How to save an entity record in CRM 2011 using javascript

In CRM 2011, you could save an entity record using javascript.

There are 3 types of save possible using javascript in CRM 2011.

1. Equivalent to 'SAVE' button found on the entity form

Xrm.Page.data.entity.save();
2. Equivalent to 'SAVE AND NEW' button found on the entity form

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

3. Equivalent to 'SAVE AND CLOSE'  button found on the entity form

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


thanks to: http://crmdm.blogspot.in/2011/06/how-to-save-entity-record-in-crm-2011.html 

Debug Plugin in Dynamics CRM 2011

In earlier versions of CRM, in order to debug any Plug-in or Custom workflow activity it was mandatory to copy the DLL and PDB files to “%Microsoft Dynamics CRM%\server\bin\assembly” directory and then attach the source code to server’s worker process i.e. w3wp.exe

Dynamics CRM 2011 provides a better mechanism by which developers can achieve the above with just few clicks and without accessing the CRM server.
Here’s how


thank to :  http://crm.ipiyush.me/debug-plugin-in-dynamics-crm-2011/

Procedure

  1. Build and register your Plugin as usual. Register Plugin
  2. Inside Plugin Registration Tool, you’ll find a button which says Install Profiler, Click it.

    Install Profiler
  3. Once it is done, you will find an entry for Plug-in Profiler beneath your assemblies.
  4. Now, go-to the step for which you want to debug your plugin and press the Profile button. Start Profiling
  5. Once done, you will see a tag (Profiled) adjacent to the step. Profiled
  6. Now go ahead and execute the plugin i.e. perform the steps in CRM that will trigger this plugin.
  7. If the code has any errors, then CRM will provide you a log file to download; go ahead and download the file. (see screenshot below) Error Log
  8. Now, inside Visual Studio, insert Breakpoints wherever you feel and use Attach to Process button and attach the code to Plugin Registration Tool exe.
    Note: Initially you will see that VS cannot find symbols so breakpoints will not be hit. Attach to Process
  9. Now, go back to Plugin Registration Tool and Select the Step which you profiled earlier hit Debug button. Debug
  10. A new Dialog-box will be presented to you, refer to the necessary files and hit Start Plug-in Execution button. Start Plug-in Execution
  11. Wait for a few seconds and you will start to see the following in Plug-in Traces window from Debug screen. Plug-in Trace
  12. Now, switch to Visual Studio and you will see that your first Breakpoint has been hit.




















    Breakpoint

Saturday, September 1, 2012

Crm 2011 - Hidding Ribbon button based on partylist value by using javascript

 function SetRibbonButtonVisiblity()
{

var approvers = Xrm.Page.getAttribute("to").getValue();
var isApprover=false;
if(approvers != null)
{
    for (var index= 0; index < approvers.length; index++)
    {
      if (approvers[index].type == 8)
       {
        var UserGUID = Xrm.Page.context.getUserId();
        if(approvers[index].id == UserGUID)
        {
        isApprover=true;
        }
       }
     }
}

if(isApprover == false)
{
var approveButton= window.top.document.getElementById("jmh_approvalrequest|NoRelationship|Form|Ntier.Form.jmh_approvalrequest.MainTab.Actions.Accept-Large");

var rejectButton= window.top.document.getElementById("jmh_approvalrequest|NoRelationship|Form|Ntier.Form.jmh_approvalrequest.MainTab.Actions.Reject-Large");


if(approveButton != null && rejectButton != null)
{
approveButton.style.display='none';
rejectButton.style.display='none';
}
}

    }

Note : you can get ribbon button id by pressing F12.
To get or set partylist
http://rajeevpentyala.wordpress.com/2012/04/02/get-and-set-partylist-fields-using-jscript/
Reference:
http://www.ahmetcankaya.com/hide-ribbon-button-in-crm-2011-by-using-javascript/