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>