Monday, 24 December 2012

Code to validate an appointment in CRM 2011


In this article , I am going to explain how to Validate an appointment

For Better Understanding I divided this article in two parts
(i)      Retrieve the appointment to be validated
(ii)     Use the Validate message

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;


Retrieve an appointment
Guid _appointmentId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");

ColumnSet cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
                    Appointment retrievedAppointment = (Appointment)_serviceProxy.Retrieve(Appointment.EntityLogicalName,
                                                               _appointmentId, cols);


Use the validate message
ValidateRequest validatedReq = new ValidateRequest();
validatedReq.Activities = new EntityCollection();
validatedReq.Activities.Entities.Add(retrievedAppointment);
validatedReq.Activities.MoreRecords = false;
validatedReq.Activities.PagingCookie = "";
validatedReq.Activities.EntityName = Appointment.EntityLogicalName;
ValidateResponse validateResp = (ValidateResponse)_serviceProxy.Execute(validatedReq);



Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    // This statement is required to enable early-bound type support.
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

           //Retrieve the appointment to be validated

            Guid _appointmentId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");
            ColumnSet cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
            Appointment retrievedAppointment =          (Appointment)_serviceProxy.Retrieve(Appointment.EntityLogicalName,
                                                       _appointmentId, cols);
         
            //Use the Validate message

            ValidateRequest validatedReq = new ValidateRequest();
            validatedReq.Activities = new EntityCollection();
            validatedReq.Activities.Entities.Add(retrievedAppointment);
            validatedReq.Activities.MoreRecords = false;
            validatedReq.Activities.PagingCookie = "";
            validatedReq.Activities.EntityName = Appointment.EntityLogicalName;
            ValidateResponse validateResp = (ValidateResponse)_serviceProxy.Execute(validatedReq);


}


Thursday, 11 October 2012

Code to book an appointment in crm 2011


In this article , I am going to explain how to Book and Validate appointment

For Better Understanding I divided this article in four parts
(i)      Get the current user information
(ii)     Create the ActivityParty instance
(iii)    Create the appointment instance
(iv)    Book request message

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Get the current user information
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);


Create the ActivityParty instance
ActivityParty party = new ActivityParty
{
    PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
};


Create the appointment instance
Appointment appointment = new Appointment
{
    Subject = " Appointment 1",
    Description = "Appointment to Book.",
    ScheduledStart = DateTime.Now.AddHours(1),
    ScheduledEnd = DateTime.Now.AddHours(2),
    Location = "Office",
    RequiredAttendees = new ActivityParty[] { party },
    Organizer = new ActivityParty[] { party }
};


Book Request message
BookRequest book = new BookRequest
{
    Target = appointment
};
BookResponse booked = (BookResponse)_serviceProxy.Execute(book);
Guid _appointmentId = booked.ValidationResult.ActivityId;


Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());


    // Get the current user information
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

    // Create the ActivityParty instance.
    ActivityParty party = new ActivityParty
    {
        PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
    };


    // Create the appointment instance.
    Appointment appointment = new Appointment
    {
        Subject = " Appointment 1",
        Description = "Appointment to Book.",
        ScheduledStart = DateTime.Now.AddHours(1),
        ScheduledEnd = DateTime.Now.AddHours(2),
        Location = "Office",
        RequiredAttendees = new ActivityParty[] { party },
        Organizer = new ActivityParty[] { party }
    };



    // Use the Book request message.
    BookRequest book = new BookRequest
    {
        Target = appointment
    };
    BookResponse booked = (BookResponse)_serviceProxy.Execute(book);
    Guid _appointmentId = booked.ValidationResult.ActivityId;

}

Wednesday, 10 October 2012

Code to retrieve the schedule of Multiple users in CRM 2011

In this article , I am going to explain how to  retrieve the schedule of Multiple users

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Complete Code
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);
    Guid _currentUserId = userResponse.UserId;

    // Create another user
    Guid _otherUserId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");
         

    // Retrieve the schedule of the current and the other user.                                            
    QueryMultipleSchedulesRequest scheduleRequest = new QueryMultipleSchedulesRequest();
    scheduleRequest.ResourceIds = new Guid[2];
    scheduleRequest.ResourceIds[0] = _currentUserId;
    scheduleRequest.ResourceIds[1] = _otherUserId;
    scheduleRequest.Start = DateTime.Now;
    scheduleRequest.End = DateTime.Today.AddDays(7);
    scheduleRequest.TimeCodes = new TimeCode[] { TimeCode.Available };

    QueryMultipleSchedulesResponse scheduleResponse = (QueryMultipleSchedulesResponse)_serviceProxy.Execute(scheduleRequest);
                   
}


Code to retrieve the schedule of a system user in CRM 2011

In this article , I am going to explain how to  retrieve the schedule of a system user

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Complete Code
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);
}

Friday, 10 August 2012

Soap XML RetrieveMultiple using javascript in CRM 2011


In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple

In this javascript code i am 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);
    }

}

Soap XML Retrieve using javascript in CRM 2011

In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/Retrieve

In this javascript code i am 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);
    }
}

Open popup window using javascript in CRM 2011

In this article , I am going to explain 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);

Set focus on control using javascript in CRM 2011

In this article , I am going to explain how to set focus on control

Set focus
Xrm.Page.getControl("attributename").setFocus(true);

Expand / Collapse tab using javascript in CRM 2011

In this article , I am going to explain how to expand and collapse tabs

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

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

Thursday, 9 August 2012

Hide and Show section using javascript in CRM 2011

In this article , I am going to explain how to hide section

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);

Hide and Show tab using javascript in CRM 2011

In this article , I am going to explain 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);

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

In this article , I am going to explain how to get only changed data

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



Get current user roles using javascript in CRM 2011

In this article , I am going to explain how to get current user roles

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



Retrieve form all controls using javascript in CRM 2011

In this article , I am going to explain how to retrieve form all controls

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

Refresh ribbon using javascript in CRM 2011

In this article , I am going to explain how to refresh current entity ribbon

Refresh ribbon
Xrm.Page.ui.refreshRibbon()



Attach event to attribute using javascript in CRM 2011

In this article , I am going to explain how to attach event to attribute

Attach event to attribute

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


Get Current user id using javascript in CRM 2011

In this article , I am going to explain how to get current user id

Get Current user id
var userID = Xrm.Page.context.getUserId();


Hide a attribute on form using javascript in CRM 2011

In this article , I am going to explain how to hide a attribute on Form

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



Set focus on control using javascript in CRM 2011

In this article , I am going to explain how to set focus on control

Set focus on control
Xrm.Page.ui.controls.get("attributename").setFocus();


Save and Close function in javascript for CRM 2011

In this article , I am going to explain javascript save and close functions

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();


Get Form type using javascript in CRM 2011

In this article , I am going to explain how to get form type

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



Get and Set control disabled using javascript in CRM 2011

In this article , I am going to explain how to get and set control disable

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);


Get Current record ID using javascript in CRM 2011

In this article , I am going to explain how to get current record id

Get current record id
var Id = Xrm.Page.data.entity.getId();



Get Server URL using javascript in CRM 2011

In this article , I am going to explain how to get crm server base URL

Get server URL
var serverURL = Xrm.Page.context.getServerUrl();



Wednesday, 8 August 2012

Get Organization Name using javascript in CRM 2011

In this article , I am going to explain how to get current organization name using javascript

Get current organization name
var orgName = Xrm.Page.context.getOrgUniqueName();



Check modified Form using javascript in CRM 2011

In this article , I am going to explain 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();



Get the current entity name using javascript in CRM 2011

In this article , I am going to explain how to get current entity name

Get current entity name
var entity = Xrm.Page.data.entity.getEntityName();

Get the label name of the attribute using javascript in CRM 2011

In this article , I am going to explain how to get attribute label value

Get attribute label name
var label = Xrm.Page.getControl("atrributename").getLabel()

Get OptionSet attribute value and text using javascript in CRM 2011

In this article , I am going to explain how to get OptionSet value and text

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

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

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

Tuesday, 7 August 2012

Set attribute requirement level using javascript in CRM 2011


In this article , I am going to explain how to set attribute requirement level using javascript

Requirement level setting
Xrm.Page.getAttribute("attributename").setRequiredLevel("none");
Xrm.Page.getAttribute("attributename").setRequiredLevel("required");
Xrm.Page.getAttribute("attributename").setRequiredLevel("recommended");

Get and Set lookup value using javascript in CRM 2011

In this article , I am going to explain how to set and get CRM lookup attribute value using javascript

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}]);


Get and Set attribute value using javascript in CRM 2011

In this article , I am going to explain how to set and get CRM attribute value using javascript

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

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

Send an Email in CRM 2011


In this article , I am going to explain how to send an email

For Better Understanding I divided this article in four parts
(i)      Create the 'From:' activity party for the email
(ii)     Create the 'To:' activity party for the email
(iii)    Create an e-mail message
(iv)    Create the request to send email

Namespace need to include 
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;

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

Create the request to send email
SendEmailRequest sendEmailreq = new SendEmailRequest
{
    EmailId = _emailId,
    TrackingToken = "",
    IssueSend = true
};

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


Complete Code
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);
}

Send an Email Using a Template in CRM 2011

In this article , I am going to explain how to send an email using template id

For Better Understanding I divided this article in four parts
(i)      Create the 'From:' activity party for the email
(ii)     Create the 'To:' activity party for the email
(iii)    Create an e-mail message
(iv)    Create the request to send email

Namespace need to include 
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;

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 = "SendEmailFromTemplate Message.",
    DirectionCode = true
};

Create the request to send email
SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
{
    Target = email,

    // Use a built-in Email Template of type "contact".
    TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

    // The regarding Id is required, and must be of the same type as the Email Template.
    RegardingId = _contactId,
    RegardingType = Contact.EntityLogicalName
};

SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);
Guid _emailId = emailUsingTemplateResp.Id;

Complete Code
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 = "SendEmailFromTemplate Message.",
        DirectionCode = true
    };

    // Create the request to send email
    SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
    {
        Target = email,

        // Use a built-in Email Template of type "contact".
        TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

        // The regarding Id is required, and must be of the same type as the Email Template.
        RegardingId = _contactId,
        RegardingType = Contact.EntityLogicalName
    };

    SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);
    Guid _emailId = emailUsingTemplateResp.Id;
}

Friday, 27 July 2012

Implement Google Map API in CRM 2011

In this article , I am going to explain how to use Google Map API in CRM 2011

In my custom entity have two attributes "new_fromaddress" and "new_toaddress" and i need to show Address Path direction using Google Map API
To display path , I created HTML web resource and in html web resource inserted two div panels
<div id ="directionpanel"  style="height: 390px;overflow: auto;width: 200px" ></div>
<div id ="map" style="height: 390px; width: 500px"></div>


To use Google API need to insert javascript Class
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

To find CRM main entity attributes need to insert Class
<script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>

To initialize Google map , need to write javascript function InitializeMap()
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    function InitializeMap() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions =
        {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);

        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directionpanel'));

        var control = document.getElementById('control');
        control.style.display = 'block';
 }


and call this function on window load event.
window.onload = InitializeMap;


To show From and To addresses Path Direction , need to write function findDirection()
function findDirection() {
        var start = window.parent.Xrm.Page.getAttribute('new_fromaddress').getValue();
        var end = window.parent.Xrm.Page.getAttribute('new_toaddress').getValue();
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
}
and called this function after InitializeMap function
findDirection();


Complete HTML web resource code 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
    <script language="javascript" type="text/javascript">
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();

        function InitializeMap() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var myOptions =
        {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
            var map = new google.maps.Map(document.getElementById("map"), myOptions);

            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('directionpanel'));

            var control = document.getElementById('control');
            control.style.display = 'block';


        }



        function findDirection() {
            var start = window.parent.Xrm.Page.getAttribute('new_fromaddress').getValue();
            var end = window.parent.Xrm.Page.getAttribute('new_toaddress').getValue();
            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

        }


        window.onload = InitializeMap;
        findDirection();
    </script>
</head>
<body>
    <table id="control">
        <tr>
            <td valign="top">
                <div id="directionpanel" style="height: 390px; overflow: auto; width: 200px">
                </div>
            </td>
            <td valign="top">
                <div id="map" style="height: 390px; width: 500px">
                </div>
            </td>
        </tr>
    </table>
</body>
</html>










Tuesday, 17 July 2012

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

In last article, I explained how to create early bound entity class and In this article, i am going to explain how to use the early bound entity classes for create,update and delete.

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 = "Navish",
   LastName = "Jain",
   Address1_Line1 = "#1429",
   Address1_City = "Chandigarh",
   Address1_StateOrProvince = " Chandigarh ",
   Address1_PostalCode = "160036",
   Telephone1 = "123-234-5678"
};
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 == "navish");
contact.JobTitle = "CRM Consultant";
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 == "navish");
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 = "Navish",
   LastName = "Jain",
   Address1_Line1 = "#1429",
   Address1_City = "Chandigarh",
   Address1_StateOrProvince = " Chandigarh ",
   Address1_PostalCode = "160036",
   Telephone1 = "123-234-5678"
};
_contactId = _serviceProxy.Create(contact);


Create Early-Bound Entity Classes with the Code Generation Tool (CrmSvcUtil.exe) in CRM 2011

In this article, I going to explain how to create early-bound entity classes with the code Generation Tool(CrmSvcUtil.exe)

You can find the utility in the SDK download package in the SDK\Bin folder.The classes created by the code generation tool are designed to be built into a class library that can be referenced by projects that use Microsoft Dynamics CRM. After you have generated the classes using the tool, you should add the file that contains the classes to your Visual Studio project or solution

Assemblies Need to Include
Microsoft.Crm.Sdk.Proxy.dll
Microsoft.Xrm.Sdk.dll

Run the Code Generation Utility
Run this utility from the SDK\Bin folder. If you run the utility from another location, the Microsoft.Xrm.Sdk.dll assembly, located in the SDK\Bin folder, must be located in the same folder

Format for running the utility from the command line 
CrmSvcUtil.exe /url:http://<servername>/<organizationname>
/XRMServices/2011/Organization.svc /out:<outputfilename>.cs /username:<username> /password:<password> /domain:<domainname> /namespace:<outputnamespace> /serviceContextName:<service context name>

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:"myname@live.com" /password:"myp@ssword!" /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:p@ssword!
     



Thursday, 12 July 2012

Insert Custom button on CRM Form using javascript in CRM 2011

In this article , I am going to explain how to insert button using javascript on CRM Form along with attribute like below image




Call this function on Form onload event and pass attribute name as parameter


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/ico_16_4210.gif" border="0" alt="Dial this number"/></button>';
        document.getElementById(attributename).style.width = "80%";
        document.getElementById(sFieldID).onclick = function () {onbuttonclick(); };
    }
}

function onbuttonclick() {
    alert('Hi');
}

Tuesday, 10 July 2012

Filter lookup values using javascript and fetchXml in CRM 2011


In this article , I am going to explain how to filter lookup using javascript.
CRM provide inbuilt functionality for filter lookup from other lookup but in this article i am filtering lookup from picklist value


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

Code to Reassigning and Publishing Workflow in CRM 2011


In this article , I am going to explain how to unpublished workflow and assigned to new user
and again changing workflow state draft to published

public static void AssignAndPublishWorkflow(ServerConnection.Configuration serverConfig,
Guid workflowid,Guid userid)
{
             using(OrganizationServiceProxy serviceProxy = new            OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credntials, serverConfig.DeviceCredentials))
            {
                 IOrganization service = (IOrganization)serviceProxy;

                 //Unpublish the workflow
                 SetStateRequest unpubReq = new SetStateRequest();
                 unpubReq.EntityMoniker = new EntityReference("workflow",workflowid);
                 unpubReq.State = new OprionSetValue(0); //draft state
                 unpubReq.Status = new OprionSetValue(1); //draft status
                 SetStateResponse unpubResp = (SetStateResponse)service.Excute(unpubReq);

                 //assign the workflow to the new User
                 AssignRequest assignReq = new AssignRequest();
                 assignReq.Target = new EntityReference("workflow",workflowid);
                 assignReq.Assignee = new EntityReference("systemuser",userid);
                 AssignResponse assignResp = (AssignResponse)service.Execute(assignReq);

                 //impersonate the new userid
                 serviceProxy.CallerId = userid;

                 //publish the workflow
                 SetStateRequest pubReq = new SetStateRequest();
                 pubReq.EntityMoniker = new EntityReference("workflow",workflowid);
                 pubReq.State = new OprionSetValue(1); //published state
                 pubReq.Status = new OprionSetValue(2); //published status
                 SetStateResponse pubResp = (SetStateResponse)service.Excute(pubReq);
           
          }
}

Create, Update , Delete Record using Javascript in CRM2011/4.0


In this article , I am going to explain how to user javascript and Soap XML to create record in CRM 2011/4.0

Creating Contact entity record

// Prepare values for the new contact.
var firstname = "Navish";
var lastname = "Jain";
var donotbulkemail = "true";
var address1_stateorprovince = "CHD";
var address1_postalcode = "160036";
var address1_line1 = "#1429/2";
var address1_city = "Chandigarh";
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='contact'>" +
"<address1_city>" + address1_city + "</address1_city>" +
"<address1_line1>" + address1_line1 + "</address1_line1>" +
"<address1_postalcode>" + address1_postalcode + "</address1_postalcode>" +
"<address1_stateorprovince>" + address1_stateorprovince + "</address1_stateorprovince>" +
"<donotbulkemail>" + donotbulkemail + "</donotbulkemail>" +
"<firstname>" + firstname + "</firstname>" +
"<lastname>" + lastname + "</lastname>" +
"</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);
// 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);
}

XML with a CreateResponse element that returns the ID for the record created


<?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">
 <soap:Body>
  <CreateResponse xmlns="http://schemas.microsoft.com/crm/2007/WebServices">
   <CreateResult>368c8b1b-851c-dd11-ad3a-0003ff9ee217</CreateResult>
  </CreateResponse>
 </soap:Body>
</soap:Envelope>




Updating Contact Record

// Prepare variables for updating a contact.
var contactId = "89a7e456-8098-bb33-b345-0003gg9ff218";
var newAddressLine1 = "#1429/2";
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='contact'>" +
"<address1_line1>" + newAddressLine1 + "</address1_line1>" +
"<contactid>" + contactId + "</contactid>" +
"</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);
// 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);
}

XML that returns a UpdateResponse


<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">
 <soap:Body>
  <UpdateResponse xmlns="http://schemas.microsoft.com/crm/2007/WebServices" />
 </soap:Body>
</soap:Envelope>




Deleting Contact record

// Identify the contact to delete.
var contactid = "89a7e456-8098-bb33-b345-0003gg9ff218";
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>"+
"<Delete xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entityName>contact</entityName>"+
"<id>"+contactid+"</id>"+
"</Delete>"+
"</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/Delete");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// 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);
}

XML that returns a DeleteResponse


<?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">
 <soap:Body>
  <DeleteResponse xmlns="http://schemas.microsoft.com/crm/2007/WebServices" />
 </soap:Body>
</soap:Envelope>

Tuesday, 26 June 2012

Code to create , retrieve ,deactivate , renew an invoiced Contract and Contract Template in CRM 2011


In this article , I am going to explain a Contract Template and several Contracts are created and also demonstrating how to create and work with the Contract entity.

For Better Understanding I divided this article in multiple part

(i)   Create and Retrieve Contract Template
(ii)  Create Contract & Contract Line Item using Contract Template
(iii) Create the clone of the contract
(iv)  Deactivate a contract
(v)   Renew an invoiced contract
(vi)  Renew the canceled contract

Namespace need to include

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;



Create and Retrieve Contract Template

 Guid _contractTemplateId;
   QueryExpression templateQuery = new QueryExpression()
   {
      EntityName = ContractTemplate.EntityLogicalName,
      ColumnSet = new ColumnSet("contracttemplateid"),
      Criteria =
      {
          Conditions =
          {
             new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT")
          }
      }
   };
   EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery);
   if (ec.Entities.Count > 0)
   {
       _contractTemplateId = ec.Entities[0].Id;
   }
   else
   {
      ContractTemplate contractTemplate = new ContractTemplate()
      {
         Name = "Sample Contract Template",
         BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly),
                            Abbreviation = "SCT",
         AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases),
         EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------"
      };
      _contractTemplateId = _serviceProxy.Create(contractTemplate);
   }

Create Contract & Contract Line Item using Contract Template

  Contract contract = new Contract()
  {
     Title = "Sample Contract",
     ContractTemplateId = new EntityReference
     {
         Id = _contractTemplateId,
         LogicalName = ContractTemplate.EntityLogicalName
     },
     CustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     BillingCustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     ActiveOn = new DateTime(2015, 1, 1),
     ExpiresOn = new DateTime(2020, 1, 1),
     BillingStartOn = new DateTime(2015, 1, 1),
     BillingEndOn = new DateTime(2020, 1, 1)
  };
  Guid _contractId = _serviceProxy.Create(contract);

  // Create a contract line item.
  ContractDetail contractLineItem = new ContractDetail()
  {
    Title = "Sample Contract Line Item",
    ContractId = new EntityReference
    {
        Id = _contractId,
        LogicalName = Contract.EntityLogicalName
    },
    CustomerId = new EntityReference
    {
       Id = _accountId,
       LogicalName = Account.EntityLogicalName
    },
    ActiveOn = new DateTime(2015, 1, 1),
    ExpiresOn = new DateTime(2020, 1, 1),
    Price = new Money(20.0M),
    TotalAllotments = 20
  };
  _serviceProxy.Create(contractLineItem);


Create the clone of the contract

  CloneContractRequest cloneRequest = new CloneContractRequest()
  {
     ContractId = _contractId,
     IncludeCanceledLines = false
  };
  CloneContractResponse cloneResponse =
                        (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;

  // Create the second clone of the contract.
  cloneRequest = new CloneContractRequest()
                    {
                        ContractId = _contractId,
                        IncludeCanceledLines = true
                    };
  cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;


Deactivate a contract

  SetStateRequest setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _firstCloneId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(2)
  };
  _serviceProxy.Execute(setStateRequest);



  // Now that the contract has been invoiced, it is possible to put
  // the contract on hold.
  setStateRequest = new SetStateRequest()
  {
     EntityMoniker = new EntityReference
     {
        Id = _firstCloneId,
        LogicalName = Contract.EntityLogicalName
     },
     State = new OptionSetValue(3),
     Status = new OptionSetValue(4)
   };
   _serviceProxy.Execute(setStateRequest);


Renew an invoiced contract

  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(3)
  };
  _serviceProxy.Execute(setStateRequest);


  // Cancel the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(4),
    Status = new OptionSetValue(5)
  };
  _serviceProxy.Execute(setStateRequest);


Renew the canceled contract

  RenewContractRequest renewRequest = new RenewContractRequest()
  {
    ContractId = _contractId,
    IncludeCanceledLines = true,
    Status = 1
  };
  RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest);

  // Retrieve Id of renewed contract.
  Guid _renewedId = ((Contract)renewResponse.Entity).ContractId.Value;




Complete Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                      serverConfig.HomeRealmUri,
                      serverConfig.Credentials,
                      serverConfig.DeviceCredentials))
{
   _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

   Guid _accountId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");

   // Create Contract Template

   // First, attempt to retrieve the Contract Template. Otherwise,
   // create the template.
   Guid _contractTemplateId;
   QueryExpression templateQuery = new QueryExpression()
   {
      EntityName = ContractTemplate.EntityLogicalName,
      ColumnSet = new ColumnSet("contracttemplateid"),
      Criteria =
      {
          Conditions =
          {
             new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT")
          }
      }
   };
   EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery);
   if (ec.Entities.Count > 0)
   {
       _contractTemplateId = ec.Entities[0].Id;
   }
   else
   {
      ContractTemplate contractTemplate = new ContractTemplate()
      {
         Name = "Sample Contract Template",
         BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly),
                            Abbreviation = "SCT",
         AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases),
         EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------"
      };
      _contractTemplateId = _serviceProxy.Create(contractTemplate);
   }




  // Create Contract

  // Create a Contract from the Contract Template.
  Contract contract = new Contract()
  {
     Title = "Sample Contract",
     ContractTemplateId = new EntityReference
     {
         Id = _contractTemplateId,
         LogicalName = ContractTemplate.EntityLogicalName
     },
     CustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     BillingCustomerId = new EntityReference
     {
        Id = _accountId,
        LogicalName = Account.EntityLogicalName
     },
     ActiveOn = new DateTime(2015, 1, 1),
     ExpiresOn = new DateTime(2020, 1, 1),
     BillingStartOn = new DateTime(2015, 1, 1),
     BillingEndOn = new DateTime(2020, 1, 1)
  };
  Guid _contractId = _serviceProxy.Create(contract);

  // Create a contract line item.
  ContractDetail contractLineItem = new ContractDetail()
  {
    Title = "Sample Contract Line Item",
    ContractId = new EntityReference
    {
        Id = _contractId,
        LogicalName = Contract.EntityLogicalName
    },
    CustomerId = new EntityReference
    {
       Id = _accountId,
       LogicalName = Account.EntityLogicalName
    },
    ActiveOn = new DateTime(2015, 1, 1),
    ExpiresOn = new DateTime(2020, 1, 1),
    Price = new Money(20.0M),
    TotalAllotments = 20
  };
  _serviceProxy.Create(contractLineItem);



  // Clone contract twice

  // Create the first clone of the contract.
  CloneContractRequest cloneRequest = new CloneContractRequest()
  {
     ContractId = _contractId,
     IncludeCanceledLines = false
  };
  CloneContractResponse cloneResponse =
                        (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;

  // Create the second clone of the contract.
  cloneRequest = new CloneContractRequest()
                    {
                        ContractId = _contractId,
                        IncludeCanceledLines = true
                    };
  cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest);
  Guid _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value;



  // Retrieve all Contracts.
  QueryExpression contractQuery = new QueryExpression()
  {
     EntityName = Contract.EntityLogicalName,
     ColumnSet = new ColumnSet("contractid"),
     Criteria =
     {
        Conditions =
        {
            new ConditionExpression("customerid", ConditionOperator.Equal, _accountId)
        }
     }
  };
  EntityCollection contracts = _serviceProxy.RetrieveMultiple(contractQuery);


  // Deactivate a cloned contract

  // In order to deactivate a contract (put it on hold), it is first
  // necessary to invoice the contract.
  SetStateRequest setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _firstCloneId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(2)
  };
  _serviceProxy.Execute(setStateRequest);



  // Now that the contract has been invoiced, it is possible to put
  // the contract on hold.
  setStateRequest = new SetStateRequest()
  {
     EntityMoniker = new EntityReference
     {
        Id = _firstCloneId,
        LogicalName = Contract.EntityLogicalName
     },
     State = new OptionSetValue(3),
     Status = new OptionSetValue(4)
   };
   _serviceProxy.Execute(setStateRequest);



  // Renew an invoiced contract

  // In order to renew a contract, it must be invoiced first, and
  // then canceled.

  // Invoice the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(1),
    Status = new OptionSetValue(3)
  };
  _serviceProxy.Execute(setStateRequest);


  // Cancel the contract.
  setStateRequest = new SetStateRequest()
  {
    EntityMoniker = new EntityReference
    {
       Id = _contractId,
       LogicalName = Contract.EntityLogicalName
    },
    State = new OptionSetValue(4),
    Status = new OptionSetValue(5)
  };
  _serviceProxy.Execute(setStateRequest);



  // Renew the canceled contract.
  RenewContractRequest renewRequest = new RenewContractRequest()
  {
    ContractId = _contractId,
    IncludeCanceledLines = true,
    Status = 1
  };
  RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest);

  // Retrieve Id of renewed contract.
  Guid _renewedId = ((Contract)renewResponse.Entity).ContractId.Value;

}