Monday 11 March 2013

Mscrm 2011 plugin syntax on opportunity lose message:


public void CloseAssociatedOpportunity(IPluginExecutionContext context, IOrganizationService service)
        {
            if (context.InputParameters.Contains("EntityMoniker") &&
                          context.InputParameters["EntityMoniker"] is EntityReference
                && context.PostEntityImages.Contains("PostImage") && context.PostEntityImages["PostImage"] is Entity)

            {
                List<Guid> opportunityIds = new List<Guid>();
                EntityReference entity = (EntityReference)context.InputParameters["EntityMoniker"];
                OptionSetValue state = (OptionSetValue)context.InputParameters["State"];
                OptionSetValue status = (OptionSetValue)context.InputParameters["Status"];

                //state 1 = Inactivate : state 0 = Activate
                if (entity.LogicalName == "tls_joborder" && state.Value == 1)
                {
                    //Fecth the associated Opportunities of the Job Order
                    opportunityIds = GetOpportunitiesIds(service, entity.Id);

                    // Fetching Opportunity selected in the Lookup
                    if(context.PostEntityImages["PostImage"].Contains("tls_opportunity")
                        && !String.IsNullOrEmpty(((EntityReference)context.PostEntityImages["PostImage"].Attributes["tls_opportunity"]).Id.ToString()))
                       opportunityIds.Add(((EntityReference)context.PostEntityImages["PostImage"].Attributes["tls_opportunity"]).Id);

                    if (opportunityIds.Count > 0)
                    {
                        foreach (Guid opprtunityId in opportunityIds)
                        {
                            CloseOpportunitiesAsLost(service, opprtunityId);
                        }
                    }

                }
            }
        }


Mscrm 2011 C# code to close the opportunity as Lost :

 public void CloseOpportunitiesAsLost(IOrganizationService service, Guid opportunityId)
        {

            Entity entity = new Entity("opportunityclose");
            entity["opportunityid"] = new EntityReference("opportunity", opportunityId);
            entity["actualend"] = DateTime.Now;
            LoseOpportunityRequest woReq = new LoseOpportunityRequest();            
            woReq.OpportunityClose = entity;
            woReq.Status = new OptionSetValue(-1);
            service.Execute(woReq);

        }

Mscrm 2011 plugin: direct fetch xml synatx  used for retrieve

 public List<Guid> GetRelatedPracticeGroupIds(IOrganizationService service, Guid accountId)
        {
            List<Guid> PracticeGroupIds = new List<Guid>();
            string fetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""true"">
                      <entity name=""lrl_practicegroup"">
                        <attribute name=""lrl_practicegroupid"" />
                        <order attribute=""lrl_name"" descending=""false"" />
                        <link-entity name=""lrl_lrl_practicegroup_account"" from=""lrl_practicegroupid"" to=""lrl_practicegroupid"" visible=""false"" intersect=""true"">
                          <link-entity name=""account"" from=""accountid"" to=""accountid"" alias=""ac"">
                            <filter type=""and"">
                              <condition attribute=""accountid"" operator=""eq"" uitype=""account"" value=""" + accountId + @""" />
                            </filter>
                          </link-entity>
                        </link-entity>
                      </entity>
                    </fetch>";

            EntityCollection Result = service.RetrieveMultiple(new FetchExpression(fetchXml));
            if (Result.Entities.Count > 0)
            {

                foreach (Entity node in Result.Entities)
                {
                    PracticeGroupIds.Add(node.Id);
                }
            }
            return PracticeGroupIds;



        }
     
        }



Update Record In mscrm 2011 form form javascript:


Soap:



function updateAccount() {
    var FORM_TYPE_UPDATE = 2;
    var formType = Xrm.Page.ui.getFormType();
    if (formType == FORM_TYPE_UPDATE) {
        // Prepare variables for updating a contact.
        var accountId = Xrm.Page.data.entity.getId();
        var parentAccount = Xrm.Page.getAttribute('parentaccountid');
        var parentAccountId;

        if (parentAccount != null) {

            var lookUpObjectValue = parentAccount.getValue();

            if ((lookUpObjectValue != null)) {

                parentAccountId = lookUpObjectValue[0].id;

            }
            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>" +
"<Update xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
"<entity xsi:type='account'>" +
"<parentaccountid>" + parentAccountId + "</parentaccountid>" +
"<accountid>" + accountId + "</accountid>" +
"</entity>" +
"</Update>" +
"</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/Update");
            xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
            xHReq.setRequestHeader("Content-Length", xml.length);
            xHReq.send(xml);
        }
    }
}




Rest:

function updateContactRest() {

    var FORM_TYPE_UPDATE = 2;
    var formType = Xrm.Page.ui.getFormType();
    if (formType == FORM_TYPE_UPDATE) {
        // Prepare variables for updating a contact.
        var accountId = Xrm.Page.data.entity.getId();
        var parentAccount = Xrm.Page.getAttribute('parentaccountid');
        var parentAccountId;

        if (parentAccount != null) {

            var lookUpObjectValue = parentAccount.getValue();

            if ((lookUpObjectValue != null)) {

                parentAccountId = lookUpObjectValue[0].id;


            }
            // Gets the record Guid
            var id = Xrm.Page.data.entity.getId();
            var changes = {
                // Text field

                // Lookup field
                ParentAccountId: {
                    Id: parentAccountId, // Guid of the parent account
                    LogicalName: "account"
                }
            };

            //updateRecord exists in JQueryRESTDataOperationFunctions.js
            updateRecord(id, changes, "AccountSet", updateAccountCompleted, null);
        }
    }
}


function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();

    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //id is required
    if (!id) {
        alert("record id is required.");
        return;
    }
    //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);

    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.          
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

            //Specify the HTTP method MERGE to update just the changes you are submitting.          
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //The MERGE does not return any data at all, so we'll add the id
            //onto the data object so it can be leveraged in a Callback. When data
            //is used in the callback function, the field will be named generically, "id"
            data = new Object();
            data.id = id;
            if (successCallback) {
                successCallback(data, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}


function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}

//Called upon successful Account update.
function updateAccountCompleted(data, textStatus, XmlHttpRequest) {
    //Get back the Account JSON object
    var account = data;
    // alert("Account updated: id = " + account.id);
}


















How to have a custom filtering on lockup using form java script in mscrm 2011: by Srinivas kalwakuntla





function Accountview() {

    var account = Xrm.Page.getAttribute('tls_parentaccount');
    var accountid;

    if (account != null) {

        var lookUpObjectValue = account.getValue();

        if ((lookUpObjectValue != null)) {

            var lookuptextvalue = lookUpObjectValue[0].name;

            var accountid = lookUpObjectValue[0].id;

        }


        if (!IsNull(accountid)) {
            var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}";
            var entityName = "account";
            var viewDisplayName = "Default View For Account";


            var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
                     '<entity name="account">' +
                        '<attribute name="name" />' +
                         '<attribute name="sic" />' +
                        '<attribute name="accountid" />' +
                         '<attribute name="address1_city" />' +
                         '<attribute name="telephone1" />' +
                         '<attribute name="primarycontactid" />' +
                         '<filter type="and">' +
                          '<condition attribute="accountid" operator="ne" value="' + accountid + '"/>' +
                        '</filter>' +
                     '</entity>' +
                  '</fetch>';

            // build Grid Layout
            var layoutXml = "<grid name='resultset' " +
                "object='1' " +
                "jump='account' " +
                "select='0' " +
                "icon='0' " +
                "preview='1'>" +
                "<row name='result' " +
                "id='accountid'>" +
                "<cell name='name' " +
                "width='200' />" +
                "<cell name='primarycontactid' " +
                "width='150' />" +
                "<cell name='sic' " +
                "width='150' />" +
                "<cell name='address1_city' " +
                "width='150' />" +
                "<cell name='telephone1' " +
                "width='150' />" +
                "</row>" +
                "</grid>";

            Xrm.Page.getControl("new_newemployer").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
            Xrm.Page.getControl("new_previousemployer").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);

        }

    }
}