Ascentium CrmService JavaScript Library

by Ercan Tüzün 11/7/2008 5:11:00 PM

Yazılım geliştiricilere CRM platformu üzerinde kolaylık sağlayacak bir javascript library si ve kullanım örnekleri.Aşağıda kaynağın linkini ve library i indirebiliceğiniz linkleri bulabilirsiniz.

 

Ascentium CrmService Samples

The CrmService.js script supports sending messages directly to the CRM 4.0 web service utilizing only JavaScript. You can use this file in your own ASPX pages, from with CRM forms or virtually anywhere.

The following methods are supported:

  • Create
  • Retrieve
  • Update
  • Delete
  • Fetch
  • Associate
  • Disassociate
  • SetState

For many of the of these you can also pass in a callback function so they can execute asynchronously.

Create, Retrieve, Update, Delete Sample

This sample shows how to Create, Retrieve, Update and Delete records within CRM. Notice when creating the Contact that to set the parentcustomerid there is a special CrmLookup object you need to use. Use this for all lookups.

function Run()
{
    //create the Ascentium_CrmService object
    var oService = new Ascentium_CrmService("MicrosoftCrm", "http://localhost:5555");

    //create an entity
    var beAccount = new BusinessEntity("account");
    beAccount.attributes["name"] = "Ascentium";
    beAccount.attributes["numberofemployees"] = 600.00;
    var sAccountId = oService.Create(beAccount);

    alert("Account Created. Account ID = " + sAccountId);

    //update an entity
    var beAccountToUpdate = new BusinessEntity("account");
    beAccountToUpdate.attributes["accountid"] = sAccountId;
    beAccountToUpdate.attributes["revenue"] = 1000000000.00;
    oService.Update(beAccountToUpdate);

    alert("Account Updated");

    //retrieve an entity
    var asCols = ["name", "revenue", "createdon", "createdby"];
    var beRetrievedAccount = oService.Retrieve("account", sAccountId, asCols);

    alert("Account Retrieved: " +
    beRetrievedAccount.attributes["name"].value + " : " +
    beRetrievedAccount.attributes["revenue"].value + " : " +
    beRetrievedAccount.attributes["createdon"].value + " : " +
    beRetrievedAccount.attributes["createdby"].value);

    //create an entity with a lookup attribute
    var beContact = new BusinessEntity("contact");
    beContact.attributes["firstname"] = "Joe";
    beContact.attributes["birthdate"] = "2008-01-01T00:00:00";
    beContact.attributes["parentcustomerid"] = new CrmLookup("account", sAccountId);
    var sContactId = oService.Create(beContact);

    alert("Contact Created: " + sContactId);

    //delete an entity
    oService.Delete("account",sAccountId);

    alert("Account Deleted");
}

Fetch Sample

This sample shows how to use the Fetch query language to pull back collections of entities based on the passed in query. For more information on the Fetch query language search for "Using FetchXML" in the CRM 4.0 SDK on MSDN.

function Fetch()
{
    //create the Ascentium_CrmService object
    var oService = new Ascentium_CrmService(orgName.value, serverUrl.value);

    //execute a Fetch query
    var sFetchXml = "<fetch mapping='logical'><entity name='account'><attribute name='accountid'/><attribute name='name'/></entity></fetch>";
    var aoFetchResult = oService.Fetch(sFetchXml);

    //iterate through the aoFetchResult collection
    var sResults = "Accounts:\n";

    for (var i = 0; i < aoFetchResult.length; i++)
    {
        var beResult = aoFetchResult[i];
        sResults += i + ": " + beResult.attributes["accountid"].value + ", " + beResult.attributes["name"].value + "\n";  
    }

    alert(sResults);
}

Asynchronous Sample

This sample shows how to use callbacks to allow the functions to perform asynchronously.

function WhoAmI()
{
    //create the Ascentium_CrmService object
    var oService = new Ascentium_CrmService(orgName.value, serverUrl.value);

    //define a fetchxml query that returns only the current user
    var sFetchXml = "<fetch mapping=\"logical\"><entity name=\"systemuser\"><attribute name=\"fullname\"/><attribute name=\"systemuserid\"/><filter type=\"and\"><condition attribute=\"systemuserid\" operator=\"eq-userid\"/></filter></entity></fetch>";

    //execute the fetch asynchronously by passing a callback function to the Fetch method
    oService.Fetch(sFetchXml, WhoAmICallback);
}

function WhoAmICallback(aoFetchResult)
{
    if (aoFetchResult.length > 0)
    {
        var beUser = aoFetchResult[0];

        alert("You are " + beUser.attributes["fullname"].value + ", System User ID = " + beUser.attributes["systemuserid"].value);
    }
}

Associate/Disassociate Sample

This sample shows how to Associate and Disassociate records. This is used when you have a many-to-many relationship. The fifth parameter is the actual name of the N:N relationship.

function Associate()
{
    //create the Ascentium_CrmService object
    var oService = new Ascentium_CrmService(orgName.value, serverUrl.value);

    //create an account
    var beAccount = new BusinessEntity("account");
    beAccount.attributes["name"] = "Ascentium";
    var sAccountId = oService.Create(beAccount);

    alert("Account Created");

    //create a lead
    var beLead = new BusinessEntity("lead");
    beLead.attributes["fullname"] = "Mr. Lead";
    var sLeadId = oService.Create(beLead);

    alert("Lead Created");

    //associate the account and the lead
    oService.Associate("account", sAccountId, "lead", sLeadId, "accountleads_association");

    alert("Account and Lead Associated");

    //disassociate them
    oService.Disassociate("account", sAccountId, "lead", sLeadId, "accountleads_association");

    alert("Account and Lead Disassociated");

    //delete the account
    oService.Delete("account", sAccountId);

    alert("Account Deleted");

    //delete the lead
    oService.Delete("lead", sLeadId);

    alert("Lead Deleted");
}

SetState Sample

This sample shows how to set the State of a record.

function SetState()
{
    //create the Ascentium_CrmService object
    var oService = new Ascentium_CrmService(orgName.value, serverUrl.value);

    //create an account
    var beAccount = new BusinessEntity("account");
    beAccount.attributes["name"] = "Ascentium";
    var sAccountId = oService.Create(beAccount);

    alert("Account Created");

    //deactivate the account
    oService.SetState("account", sAccountId, "Inactive", -1);

    alert("Account State set to Inactive");

    //delete the account
    oService.Delete("account", sAccountId);

    alert("Account Deleted");
}

 

http://www.ascentium.com/blog/crm/Post129.aspx

 

 

AscentiumCrmService.zip (7,43 kb)

CRM 4.0 da javascript kullanarak workflow çalıştırmak,çağırmak ve başlatmak

by Ercan Tüzün 11/7/2008 5:04:00 PM

/* the function */
ExecuteWorkflow = function(entityId, workflowId)
{
    
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>" + 
    
"    <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + 
    
"      <Request xsi:type=\"ExecuteWorkflowRequest\">" + 
    
"        <EntityId>" + entityId + "</EntityId>" + 
    
"        <WorkflowId>" + workflowId + "</WorkflowId>" + 
    
"      </Request>" + 
    
"    </Execute>" + 
    
"  </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/Execute");
    
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    
xmlHttpRequest.send(xml);
    
var resultXml = xmlHttpRequest.responseXML;
    
return(resultXml.xml);
} 

/* call */ 

var theWorkflowId = "3FD2DD58-4708-43D7-A21B-F0F90A0AA9F2";
//change to your workflow Id 

ExecuteWorkflow(crmForm.ObjectId, theWorkflowId);

Crm formlarında javascript ile crm web servislerini kullanmak

by Ercan Tüzün 5/24/2008 9:13:00 PM

Crm fromlarında yapacağımız işlemler için bazen crm web servislerini kullanmamız gerekir.Mesela account entity sinde primary contact lookup ına ilişkili contact ın mail adresine veya başka bir attributune ihtiyaç duyabiliriz bu ihttiyaç başka entity  ilşişkilerindede oluşabilir.Bazı işlemler içinse entityler arasında ilişki olmasına gerek yoktur.Yani  fromun ve field ların  eventlerinde crm servislerini kullanarak veri sorgulaması yapmak istediğimizde fetch xml e başvururuz.Fetch xml ile veri sorgulamak için ise crm servisini kullanan bir SOAP (Simple Object Access Protocol) nesnesi oluşturmamız gerekir.

SOAP Nedir?

   Veri sorgulamasının yapılabilmesi için istemci ve web servisi arasındaki haberleşmeyi sağlayacak bir Proxy nesnesi oluşturmamız gerekir.İstemci uygulama crm servisini kullanmak istediğinde, yani bu servis üzerinden bir metodu çağırmak istediğinde, bu talebi proxy nesnesinden ister. Proxy nesnesi ise bu talebi , web servisine iletir. Web servisi gelen talebi değerlendirir ve ürettiği cevabı yine istemci uygulamadaki proxy nesnesine gönderir. Proxy nesneside sonuçları, uygulama ortamına iletir.

  

 İstemci uygulama, proxy nesnesinde normal olarak talepte bulunur ve cevapları alır. Buradaki ilişki normal olarak bir nesne.metod ilişkisidir. Ancak proxy nesnesi bu mesajları, esnek, kolay okunabilir, herhangibir engele takılmayacak bir hale getirmek durumundadır. Bu iş için XML tabanlı bir bilgi akışı kullanılır. Yinede hareket edecek mesajların uygun bir formasyonda taşınmaları ve web servisinin anlayabileceği bir dilde ifade edilebilmeleri daha doğrudur. Bu noktada SOAP (Simple Object Access Protocol – Basit Nesne Erişim Antlaşması)  devreye girer.SOAP, web servisleri ve istemciler arasında gidip gelecek mesajların, XML tabanlı olarak belirlendiği standartlara uygun formatta taşınmasını sağlayan bir protokoldür.

 SOAP protokolü, web servisleri ile istemciler arasında gerçekleştirilen veri alışverişinde, karşılıklı olarak akıcak mesajların nasıl ve ne şekilde paketleneceğini yada başka bir deyişle bilgilerin nasıl kapsülleneceğini belirtir. SOAP, özünde XML tabanlı mesajların oluşturulmasını belirtir. Bu nedenle SOAP protokolünü uygulayan mesajlar (ki bunlar SOAP Mesajı olarak adlandırılır), herhangibir ağ ortamında hiç bir sorunla karşılaşmadan uzak makineler arasında iletilebilirler. SOAP protokolü, 4 temel üzerine inşa edilmiştir.

-Envelope (Zarf)

-Veri Kodlama Kuralları (Data Encoding Rules)

-Mesaj Değişim Modeli (Message Exchange Model)

-Veri Bağlama

 SOAP protokolünün dayandığı bu temel kurallar içerisinde en önemlisi Envelope kısmıdır. Bir SOAP mesajı mutlaka bir zarf olarak teşkil edilmeli ve Zarf kurallarına göre tasarlanmalıdır.Bir soap zarfı soap header ve soap body den oluşur. SOAP Body kısmında yapılan metod çağırımlarına ilişkin bilgiler ile çağrı sonucu istemcilere gönderilecek cevaplara ait xml tabanlı bilgiler yer alır.  Diğer temellerin uygulanması zorunlu değildir. Veri kodlama kuralları, özellikle serileştirilen nesneler için bir model sunar.

Örnek bir javascript kodu ile işlemin nasıl yapılacağını görelim:

Account formumuzun onload() eventine aşağıdaki kodu yazalım.

 

var fetchXml = "<fetch mapping='logical'>" + "<entity name='contact'>" + "<attribute name='emailaddress1'/>" +

"<filter type='and'>" +

"<condition attribute='contactid' operator='eq' value='" + crmForm.all.primarycontactid.DataValue[0].id + "' />" +

 "</filter>" +

"</entity>" + "</fetch>";

 

var xmlDoc = createSOAPMessage(fetchXml);

var xmlVal= xmlDoc.selectSingleNode("resultset/result/emailaddress1");

var emailaddress=xmlVal.text;

alert(emailaddress);

function createSOAPMessage(fetchXml)

{

var soapHeaderXml = "<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>";

var soapFooterXml = "</soap:Body></soap:Envelope>";

// XMl encode

fetchXml = fetchXml.replace(/&/g, '&amp;');

fetchXml = fetchXml.replace(/</g, '&lt;');fetchXml = fetchXml.replace(/>/g,

'&gt;');

fetchXml = fetchXml.replace(/'/g, '&apos;');

fetchXml = fetchXml.replace(/"/g, '&quot;');

fetchXml = "<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +

"<fetchXml>" + fetchXml + "</fetchXml>" +

"</Fetch>";

 

var soapXml = soapHeaderXml + fetchXml + soapFooterXml;

 

var crmServiceUrl = SERVER_URL.replace(ORG_UNIQUE_NAME,"");

crmServiceUrl += "mscrmservices/2007/crmservice.asmx"

// Create the XMLHTTP object for the execute method.

var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

xmlhttp.open("POST", crmServiceUrl , false);xmlhttp.setRequestHeader(

"Content-Type", "text/xml; charset=utf-8");xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");

 

//Send the XMLHTTP object.

xmlhttp.send(soapXml);

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;

xmlDoc.loadXML(xmlhttp.responseXML.text);

return xmlDoc; }

formumuzu publish edip örnek bir kayıt için çalıştırırsak mail adresinin bize döndüğünü görebiliriz.

İyi Çalışmalar...

Blogging by Ercan TUZUN

Yazar Hakkında

Ercan TÜZÜN Ercan TÜZÜN
Computer Engineer
Software Developer.

E-mail me Send mail

Takvim

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments

Don't show

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Sign in