Tuesday, December 29, 2009

Update Method using Java Script

Hi,
Here is an example to update entoty request only in Client Side

// Prepare variables for updating a contact.
var contactId = "56914948-991C-DD11-AD3A-0003FF9EE217";
var newAddressLine1 = "34 Market St.";
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);
}
// Display a confirmation message and open the updated contact.
else
{
alert("Contact with id = "+contactId+" successfully updated.");
window.open("/sfa/conts/edit.aspx?id={"+contactId+"}");
}

Enjoy,
Rami Heleg

RetrieveMultiple Method Using Java Script

Hi,
Here is an example to RetrieveMultiple only in Client Side

// Prepare variables to retrieve the contacts.
var searchCity = "Sammamish";
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>"+
"<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>fullname</q1:Attribute>"+
"<q1:Attribute>contactid</q1:Attribute>"+
"</q1:Attributes>"+
"</q1:ColumnSet>"+
"<q1:Distinct>false</q1:Distinct>"+
"<q1:Criteria>"+
"<q1:FilterOperator>And</q1:FilterOperator>"+
"<q1:Conditions>"+
"<q1:Condition>"+
"<q1:AttributeName>address1_city</q1:AttributeName>"+
"<q1:Operator>Like</q1:Operator>"+
"<q1:Values>"+
"<q1:Value xsi:type='xsd:string'>"+searchCity+"</q1:Value>"+
"</q1:Values>"+
"</q1:Condition>"+
"</q1:Conditions>"+
"</q1:Criteria>"+
"</query>"+
"</RetrieveMultiple>"+
"</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/RetrieveMultiple");
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);
}
Enjoy,
Rami Heleg

Retrieve Method Using JScript

Hi,
Here is an example to retrieve data only in Client Side

// Prepare variables for a contact to retrieve.
var contactid = "4696f8cb-9a1c-dd11-ad3a-0003ff9ee217";
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>"+
"<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entityName>contact</entityName>"+
"<id>"+contactid+"</id>"+
"<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>"+
"<q1:Attributes>"+
"<q1:Attribute>fullname</q1:Attribute>"+
"</q1:Attributes>"+
"</columnSet>"+
"</Retrieve>"+
"</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/Retrieve");
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);
}
// Display the retrieved value.
else
{
alert(resultXml.selectSingleNode("//q1:fullname").nodeTypedValue);
}
The following is an example of a successful response:

<?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>
<RetrieveResponse xmlns="http://schemas.microsoft.com/crm/2007/WebServices">
<RetrieveResult xmlns:q1="http://schemas.microsoft.com/crm/2007/WebServices" xsi:type="q1:contact">
<q1:fullname>Jesper Aaberg</q1:fullname>
<q1:contactid>{4696F8CB-9A1C-DD11-AD3A-0003FF9EE217}</q1:contactid>
<q1:owningbusinessunit>{0EA35030-3EC9-DC11-A8D2-0003FF9EE217}</q1:owningbusinessunit>
</RetrieveResult>
</RetrieveResponse>
</soap:Body>
</soap:Envelope>

Enjoy,
Rami Heleg

Run Fetch Method using java script

Hi,
Here is an example to execute fetch only in Client Side

// Prepare variables to fetch accounts.
var fetchMapping = "logical";
var entityName = "account";
var firstColumn = "accountid";
var secondColumn = "name";
var linkEntity = "systemuser";
var linkEntityTo ="owninguser";
var filterType = "and";
var conditionAttribute = "lastname";
var operator = "ne";
var value = "Cannon";
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>"+
"<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<fetchXml><fetch mapping='"+fetchMapping+"'>"+
"<entity name='"+entityName+"'>"+
"<attribute name='"+firstColumn+"'/>"+
"<attribute name='"+secondColumn+"'/>"+
"<link-entity name='"+linkEntity+"' to='"+linkEntityTo+"'>"+
"<filter type='"+filterType+"'>"+
"<condition attribute='"+conditionAttribute+"'"+
" operator='"+operator+"' value='"+value+"'/>"+
"</filter>"+
"</link-entity>"+
"</entity>"+
"</fetch></fetchXml>"+
"</Fetch>"+
"</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/Fetch");
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);
}

Enjoy,
Rami Heleg

Execute Method using Java Script

Hi,
Here is an example to execute request only in Client Side

// Prepare variables to add a new product to a campaign.
var CampaignId = "771ed82b-6b27-dd11-b452-0003ff9ee217";
var EntityId = "3F26C82A-A2E1-DC11-A277-001AA0B84538";
var EntityName = "product";
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>"+
"<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<Request xsi:type='AddItemCampaignRequest'>"+
"<CampaignId>"+CampaignId+"</CampaignId>"+
"<EntityId>"+EntityId+"</EntityId>"+
"<EntityName>"+EntityName+"</EntityName>"+
"</Request>"+
"</Execute>"+
"</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/Execute");
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);
}
// Display a confirmation message and open the campaign record.
else
{
alert("Product with id = "+EntityId+" successfully added to Campaign with id = "+CampaignId+".");
window.open("/ma/camps/edit.aspx?id={"+CampaignId+"}");
}


Enjoy,
Rami Heleg

Delete Entity in Client Side ( Java Script only)

Hi,
here is an example to delete entity only in client side:


// Identify the contact to delete.
var contactid = "57a4e111-7027-dd11-b452-0003ff9ee217";
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);
}
// Display confirmation message.
else
{
alert("Contact with id = "+contactid+" successfully deleted");
}

Enjoy,
Rami Heleg

Create Entity in client side ( Java Script only)

Hi,
here is an example of create entity only in client side:

// Prepare values for the new contact.

var firstname = "Jesper";
var lastname = "Aaberg";
var donotbulkemail = "true";
var address1_stateorprovince = "MT";
var address1_postalcode = "99999";
var address1_line1 = "23 Market St.";
var address1_city = "Sammamish";
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);
}
// Open new contact record if no errors.
else
{
var contactid = resultXml.selectSingleNode("//CreateResult");
window.open("/sfa/conts/edit.aspx?id={"+contactid.nodeTypedValue+"}");
}


Enjoy,
Rami Heleg

Tuesday, December 22, 2009

How to add supported JavaScript to pages.

Example how to add to pages JS supported by Microsoft:

1.
Create Folder under ISV



2.
add JavaScript code to page:



3.
add the next code into contact page:
var request = new ActiveXObject("Msxml2.XMLHTTP");
request.open("GET", "/isv/MyScripts/contact.js", false);
request.send(null);
eval(request.responseText);

For instance:



4.
open contact page and get the message.




Enjoy,
Rami Heleg

How to init Value on Server side

This example contain how to init all CRM Values:
CrmDateTime lDateTime = new CrmDateTime("2009/8/27T17:00:00");

CrmBoolean lBoolean = new CrmBoolean(true);

Picklist lList = new Picklist(1);

CrmDecimal lDec = new CrmDecimal(10.1);

CrmFloat lfloat = new CrmFloat(10.2);

CrmNumber lNumber = new CrmNumber(10);

Lookup oSys = new Lookup("systemuser", userId);

Owner owner = new Owner("systemuser", systemUserId);

Status lStatus = new Status(1);

EntityNameReference oReference = new EntityNameReference("systemuser");

Key key = new Key(userId);

CrmMoney lMoney = new CrmMoney(10.00);

Enjoy,
Rami Heleg

Thursday, December 3, 2009

Crm 4.0 Microsoft CRM Asynchronous failed and require restart

Hi
Error Message:

Exception type: CrmException
Exception message: The key specified to compute a hash value is expired, only active keys are valid. Expired Key : CrmKey(Id:c1bef2e2-efc5-de11-b538-005056a75caa, ScaleGroupId:00000000-0000-0000-0000-000000000000,
KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:10/31/2009 07:34:57, ExpiresOn:12/03/2009 07:34:57, CreatedOn:10/31/2009 07:34:57, CreatedBy:NT AUTHORITY\NETWORK SERVICE.

This problem occurs because Microsoft Dynamics CRM 4.0 uses the name of the SQL server that is in the organization table of the mscrm_config database when Microsoft Dynamics CRM 4.0 tries to connect to the SQL server. If the name is lowercase, the Async service cannot correctly process the jobs in the ScaleGroupOrganizationMaintenanceJobs table. The SqlServerName name must be the same as the value that is returned by the @@servername global variable.

Because of that the solution is to install Rollup 7.0

Microsoft Articles:

<a href="http://support.microsoft.com/kb/949844"></a>
<a href="http://support.microsoft.com/kb/949256/"></a>

Thanks and enjoy,
Rami Heleg

How to change due date filter default value for activities page:


Sometimes you need to define your default filter values for the home activities page.


Here is an example how to change due date filter default value:

Add this code to "\CRMWeb\Workplace\home_activities.aspx" page:

<script runat="server">
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
this.crmDateSelector.Selected = "Today";
this.crmGrid.Parameters.Add("scheduledend", "Today");
}
</script>

You can set these values to the crmDateSelector control:
Overdue
Today
Tomorrow
NextXDays;7
NextXDays;30
NextXDays;90
NextXMonths;6
NextXMonths;12
All

thanks,
Max Shafranski,
Team blog member.

Wednesday, December 2, 2009

List of events for each entity.

List of events for each entity.

Message Primary Entity
AddItem Campaign
AddItem CampaignActivity
AddMember List
AddMembers Team
AddProductToKit NULL
Assign Account
Assign Annotation
Assign Appointment
Assign Campaign
Assign CampaignActivity
Assign CampaignResponse
Assign Contact
Assign Contract
Assign CustomerOpportunityRole
Assign CustomerRelationship
Assign Email
Assign Fax
Assign Incident
Assign IncidentResolution
Assign Invoice
Assign Lead
Assign Letter
Assign List
Assign Opportunity
Assign OpportunityClose
Assign OrderClose
Assign PhoneCall
Assign Quote
Assign QuoteClose
Assign SalesOrder
Assign ServiceAppointment
Assign Task
Assign Template
Assign UserQuery
BackgroundSend Email
Book Appointment
Book ServiceAppointment
Cancel Contract
Cancel SalesOrder
CheckIncoming Email
CheckPromote Email
Clone Contract
Close Incident
Close Quote
Create Account
Create ActivityMimeAttachment
Create Annotation
Create Appointment
Create BusinessUnit
Create BusinessUnitNewsArticle
Create Calendar
Create Campaign
Create CampaignActivity
Create CampaignResponse
Create Competitor
Create Contact
Create Contract
Create ContractDetail
Create ContractTemplate
Create custom entity
Create CustomerAddress
Create CustomerOpportunityRole
Create CustomerRelationship
Create Discount
Create DiscountType
Create Email
Create Equipment
Create Fax
Create Incident
Create IncidentResolution
Create Invoice
Create InvoiceDetail
Create KbArticle
Create KbArticleComment
Create KbArticleTemplate
Create Lead
Create Letter
Create List
Create Opportunity
Create OpportunityClose
Create OpportunityProduct
Create OrderClose
Create PhoneCall
Create PriceLevel
Create Product
Create ProductPriceLevel
Create Queue
Create Quote
Create QuoteClose
Create QuoteDetail
Create Role
Create SalesLiterature
Create SalesLiteratureItem
Create SalesOrder
Create SalesOrderDetail
Create Service
Create ServiceAppointment
Create Site
Create Subject
Create SystemUser
Create Task
Create Team
Create Template
Create Territory
Create TransactionCurrency
Create UoM
Create UoMSchedule
CreateUoMSchedule UoMSchedule
Delete Account
Delete ActivityMimeAttachment
Delete Annotation
Delete Appointment
Delete BusinessUnitNewsArticle
Delete Calendar
Delete Campaign
Delete CampaignActivity
Delete CampaignResponse
Delete Competitor
Delete Contact
Delete Contract
Delete ContractDetail
Delete ContractTemplate
Delete custom entity
Delete CustomerAddress
Delete CustomerOpportunityRole
Delete CustomerRelationship
Delete Discount
Delete DiscountType
Delete Email
Delete Equipment
Delete Fax
Delete Incident
Delete IncidentResolution
Delete Invoice
Delete InvoiceDetail
Delete KbArticle
Delete KbArticleComment
Delete KbArticleTemplate
Delete Lead
Delete Letter
Delete List
Delete Opportunity
Delete OpportunityClose
Delete OpportunityProduct
Delete OrderClose
Delete PhoneCall
Delete PriceLevel
Delete Product
Delete ProductPriceLevel
Delete Queue
Delete Quote
Delete QuoteClose
Delete QuoteDetail
Delete Role
Delete SalesLiterature
Delete SalesLiteratureItem
Delete SalesOrder
Delete SalesOrderDetail
Delete Service
Delete ServiceAppointment
Delete Site
Delete Subject
Delete Task
Delete Template
Delete Territory
Delete TransactionCurrency
Delete UoM
Delete UoMSchedule
Delete UserQuery
DeliverIncoming Email
DeliverPromote Email
DetachFromQueue Email
Execute NULL
ExecuteById SavedQuery
ExecuteById UserQuery
Export NULL
ExportAll NULL
ExportCompressed NULL
ExportCompressedAll NULL
GrantAccess Account
GrantAccess Annotation
GrantAccess Appointment
GrantAccess Campaign
GrantAccess CampaignActivity
GrantAccess CampaignResponse
GrantAccess Contact
GrantAccess Contract
GrantAccess CustomerOpportunityRole
GrantAccess CustomerRelationship
GrantAccess Email
GrantAccess Fax
GrantAccess Incident
GrantAccess IncidentResolution
GrantAccess Invoice
GrantAccess Lead
GrantAccess Letter
GrantAccess List
GrantAccess Opportunity
GrantAccess OpportunityClose
GrantAccess OrderClose
GrantAccess PhoneCall
GrantAccess Quote
GrantAccess QuoteClose
GrantAccess SalesOrder
GrantAccess ServiceAppointment
GrantAccess Task
GrantAccess Template
GrantAccess UserQuery
Handle Appointment
Handle CampaignActivity
Handle CampaignResponse
Handle Email
Handle Fax
Handle Incident
Handle Letter
Handle PhoneCall
Handle ServiceAppointment
Handle Task
Import NULL
ImportAll NULL
ImportCompressedAll NULL
ImportCompressedWithProgress NULL
ImportWithProgress NULL
LockInvoicePricing NULL
LockSalesOrderPricing NULL
Lose Opportunity
Merge Account
Merge Contact
Merge Lead
ModifyAccess Account
ModifyAccess Annotation
ModifyAccess Appointment
ModifyAccess Campaign
ModifyAccess CampaignActivity
ModifyAccess CampaignResponse
ModifyAccess Contact
ModifyAccess Contract
ModifyAccess CustomerOpportunityRole
ModifyAccess CustomerRelationship
ModifyAccess Email
ModifyAccess Fax
ModifyAccess Incident
ModifyAccess IncidentResolution
ModifyAccess Invoice
ModifyAccess Lead
ModifyAccess Letter
ModifyAccess List
ModifyAccess Opportunity
ModifyAccess OpportunityClose
ModifyAccess OrderClose
ModifyAccess PhoneCall
ModifyAccess Quote
ModifyAccess QuoteClose
ModifyAccess SalesOrder
ModifyAccess ServiceAppointment
ModifyAccess Task
ModifyAccess Template
ModifyAccess UserQuery
Publish NULL
PublishAll NULL
RemoveBinaryData ActivityMimeAttachment
RemoveBinaryData Annotation
RemoveBinaryData SalesLiteratureItem
RemoveItem Campaign
RemoveItem CampaignActivity
RemoveMember List
RemoveMembers Team
RemoveProductFromKit NULL
RemoveRelated Invoice
RemoveRelated Lead
RemoveRelated Lead
RemoveRelated Opportunity
RemoveRelated Opportunity
RemoveRelated Opportunity
RemoveRelated Product
RemoveRelated Product
RemoveRelated Quote
RemoveRelated SalesLiterature
RemoveRelated SalesLiterature
RemoveRelated SalesOrder
Reschedule Appointment
Reschedule ServiceAppointment
Retrieve Account
Retrieve ActivityMimeAttachment
Retrieve ActivityPointer
Retrieve Annotation
Retrieve Appointment
Retrieve BusinessUnitNewsArticle
Retrieve Calendar
Retrieve Campaign
Retrieve CampaignActivity
Retrieve CampaignResponse
Retrieve Competitor
Retrieve Contact
Retrieve Contract
Retrieve ContractDetail
Retrieve ContractTemplate
Retrieve custom entity
Retrieve CustomerAddress
Retrieve CustomerOpportunityRole
Retrieve CustomerRelationship
Retrieve Discount
Retrieve DiscountType
Retrieve Email
Retrieve Equipment
Retrieve Fax
Retrieve Incident
Retrieve IncidentResolution
Retrieve Invoice
Retrieve InvoiceDetail
Retrieve KbArticle
Retrieve KbArticleComment
Retrieve KbArticleTemplate
Retrieve Lead
Retrieve Letter
Retrieve List
Retrieve Opportunity
Retrieve OpportunityClose
Retrieve OpportunityProduct
Retrieve OrderClose
Retrieve PhoneCall
Retrieve PriceLevel
Retrieve Product
Retrieve ProductPriceLevel
Retrieve Queue
Retrieve Quote
Retrieve QuoteClose
Retrieve QuoteDetail
Retrieve SalesLiterature
Retrieve SalesLiteratureItem
Retrieve SalesOrder
Retrieve SalesOrderDetail
Retrieve SavedQuery
Retrieve Service
Retrieve ServiceAppointment
Retrieve Site
Retrieve Subject
Retrieve Task
Retrieve Team
Retrieve Template
Retrieve Territory
Retrieve UoM
Retrieve UoMSchedule
Retrieve UserQuery
RetrieveExchangeRate NULL
RetrieveMultiple Account
RetrieveMultiple ActivityMimeAttachment
RetrieveMultiple ActivityPointer
RetrieveMultiple Annotation
RetrieveMultiple Appointment
RetrieveMultiple BusinessUnitNewsArticle
RetrieveMultiple Calendar
RetrieveMultiple Campaign
RetrieveMultiple CampaignActivity
RetrieveMultiple CampaignResponse
RetrieveMultiple Competitor
RetrieveMultiple Contact
RetrieveMultiple Contract
RetrieveMultiple ContractDetail
RetrieveMultiple ContractTemplate
RetrieveMultiple custom entity
RetrieveMultiple CustomerAddress
RetrieveMultiple CustomerOpportunityRole
RetrieveMultiple CustomerRelationship
RetrieveMultiple Discount
RetrieveMultiple DiscountType
RetrieveMultiple Email
RetrieveMultiple Equipment
RetrieveMultiple Fax
RetrieveMultiple Incident
RetrieveMultiple IncidentResolution
RetrieveMultiple Invoice
RetrieveMultiple InvoiceDetail
RetrieveMultiple KbArticle
RetrieveMultiple KbArticleComment
RetrieveMultiple KbArticleTemplate
RetrieveMultiple Lead
RetrieveMultiple Letter
RetrieveMultiple List
RetrieveMultiple Opportunity
RetrieveMultiple OpportunityClose
RetrieveMultiple OpportunityProduct
RetrieveMultiple OrderClose
RetrieveMultiple PhoneCall
RetrieveMultiple PriceLevel
RetrieveMultiple Product
RetrieveMultiple ProductPriceLevel
RetrieveMultiple Queue
RetrieveMultiple Quote
RetrieveMultiple QuoteClose
RetrieveMultiple QuoteDetail
RetrieveMultiple SalesLiterature
RetrieveMultiple SalesLiteratureItem
RetrieveMultiple SalesOrder
RetrieveMultiple SalesOrderDetail
RetrieveMultiple SavedQuery
RetrieveMultiple Service
RetrieveMultiple ServiceAppointment
RetrieveMultiple Site
RetrieveMultiple Subject
RetrieveMultiple Task
RetrieveMultiple Team
RetrieveMultiple Template
RetrieveMultiple Territory
RetrieveMultiple UoM
RetrieveMultiple UoMSchedule
RetrieveMultiple UserQuery
RetrievePrincipalAccess Account
RetrievePrincipalAccess Annotation
RetrievePrincipalAccess Appointment
RetrievePrincipalAccess Campaign
RetrievePrincipalAccess CampaignActivity
RetrievePrincipalAccess CampaignResponse
RetrievePrincipalAccess Contact
RetrievePrincipalAccess Contract
RetrievePrincipalAccess CustomerOpportunityRole
RetrievePrincipalAccess CustomerRelationship
RetrievePrincipalAccess Email
RetrievePrincipalAccess Fax
RetrievePrincipalAccess Incident
RetrievePrincipalAccess IncidentResolution
RetrievePrincipalAccess Invoice
RetrievePrincipalAccess Lead
RetrievePrincipalAccess Letter
RetrievePrincipalAccess List
RetrievePrincipalAccess Opportunity
RetrievePrincipalAccess OpportunityClose
RetrievePrincipalAccess OrderClose
RetrievePrincipalAccess PhoneCall
RetrievePrincipalAccess Quote
RetrievePrincipalAccess QuoteClose
RetrievePrincipalAccess SalesOrder
RetrievePrincipalAccess ServiceAppointment
RetrievePrincipalAccess Task
RetrievePrincipalAccess Template
RetrievePrincipalAccess UserQuery
RetrieveSharedPrincipalsAndAccess Account
RetrieveSharedPrincipalsAndAccess Annotation
RetrieveSharedPrincipalsAndAccess Appointment
RetrieveSharedPrincipalsAndAccess Campaign
RetrieveSharedPrincipalsAndAccess CampaignActivity
RetrieveSharedPrincipalsAndAccess CampaignResponse
RetrieveSharedPrincipalsAndAccess Contact
RetrieveSharedPrincipalsAndAccess Contract
RetrieveSharedPrincipalsAndAccess CustomerOpportunityRole
RetrieveSharedPrincipalsAndAccess CustomerRelationship
RetrieveSharedPrincipalsAndAccess Email
RetrieveSharedPrincipalsAndAccess Fax
RetrieveSharedPrincipalsAndAccess Incident
RetrieveSharedPrincipalsAndAccess IncidentResolution
RetrieveSharedPrincipalsAndAccess Invoice
RetrieveSharedPrincipalsAndAccess Lead
RetrieveSharedPrincipalsAndAccess Letter
RetrieveSharedPrincipalsAndAccess List
RetrieveSharedPrincipalsAndAccess Opportunity
RetrieveSharedPrincipalsAndAccess OpportunityClose
RetrieveSharedPrincipalsAndAccess OrderClose
RetrieveSharedPrincipalsAndAccess PhoneCall
RetrieveSharedPrincipalsAndAccess Quote
RetrieveSharedPrincipalsAndAccess QuoteClose
RetrieveSharedPrincipalsAndAccess SalesOrder
RetrieveSharedPrincipalsAndAccess ServiceAppointment
RetrieveSharedPrincipalsAndAccess Task
RetrieveSharedPrincipalsAndAccess Template
RetrieveSharedPrincipalsAndAccess UserQuery
RevokeAccess Account
RevokeAccess Annotation
RevokeAccess Appointment
RevokeAccess Campaign
RevokeAccess CampaignActivity
RevokeAccess CampaignResponse
RevokeAccess Contact
RevokeAccess Contract
RevokeAccess CustomerOpportunityRole
RevokeAccess CustomerRelationship
RevokeAccess Email
RevokeAccess Fax
RevokeAccess Incident
RevokeAccess IncidentResolution
RevokeAccess Invoice
RevokeAccess Lead
RevokeAccess Letter
RevokeAccess List
RevokeAccess Opportunity
RevokeAccess OpportunityClose
RevokeAccess OrderClose
RevokeAccess PhoneCall
RevokeAccess Quote
RevokeAccess QuoteClose
RevokeAccess SalesOrder
RevokeAccess ServiceAppointment
RevokeAccess Task
RevokeAccess Template
RevokeAccess UserQuery
Route Appointment
Route CampaignActivity
Route CampaignResponse
Route Email
Route Fax
Route Incident
Route Letter
Route PhoneCall
Route ServiceAppointment
Route Task
Send Email
Send Fax
Send Template
SendFromTemplate Email
SetRelated Invoice
SetRelated Lead
SetRelated Lead
SetRelated Opportunity
SetRelated Opportunity
SetRelated Opportunity
SetRelated Product
SetRelated Product
SetRelated Quote
SetRelated SalesLiterature
SetRelated SalesLiterature
SetRelated SalesOrder
SetState Account
SetState Appointment
SetState BusinessUnit
SetState Campaign
SetState CampaignActivity
SetState CampaignResponse
SetState Contact
SetState Contract
SetState ContractDetail
SetState custom entity
SetState DiscountType
SetState Email
SetState Fax
SetState Incident
SetState IncidentResolution
SetState Invoice
SetState KbArticle
SetState Lead
SetState Letter
SetState List
SetState Opportunity
SetState OpportunityClose
SetState OrderClose
SetState PhoneCall
SetState PriceLevel
SetState Product
SetState Quote
SetState QuoteClose
SetState SalesOrder
SetState ServiceAppointment
SetState Task
SetState TransactionCurrency
SetState UserQuery
SetStateDynamicEntity Account
SetStateDynamicEntity Appointment
SetStateDynamicEntity BusinessUnit
SetStateDynamicEntity Campaign
SetStateDynamicEntity CampaignActivity
SetStateDynamicEntity CampaignResponse
SetStateDynamicEntity Contact
SetStateDynamicEntity Contract
SetStateDynamicEntity ContractDetail
SetStateDynamicEntity custom entity
SetStateDynamicEntity DiscountType
SetStateDynamicEntity Email
SetStateDynamicEntity Fax
SetStateDynamicEntity Incident
SetStateDynamicEntity IncidentResolution
SetStateDynamicEntity Invoice
SetStateDynamicEntity KbArticle
SetStateDynamicEntity Lead
SetStateDynamicEntity Letter
SetStateDynamicEntity List
SetStateDynamicEntity Opportunity
SetStateDynamicEntity OpportunityClose
SetStateDynamicEntity OrderClose
SetStateDynamicEntity PhoneCall
SetStateDynamicEntity PriceLevel
SetStateDynamicEntity Product
SetStateDynamicEntity Quote
SetStateDynamicEntity QuoteClose
SetStateDynamicEntity SalesOrder
SetStateDynamicEntity ServiceAppointment
SetStateDynamicEntity Task
SetStateDynamicEntity TransactionCurrency
SetStateDynamicEntity UserQuery
UnlockInvoicePricing NULL
UnlockSalesOrderPricing NULL
Update Account
Update ActivityMimeAttachment
Update Annotation
Update Appointment
Update BusinessUnit
Update BusinessUnitNewsArticle
Update Calendar
Update Campaign
Update CampaignActivity
Update CampaignResponse
Update Competitor
Update Contact
Update Contract
Update ContractDetail
Update ContractTemplate
Update CustomerAddress
Update CustomerOpportunityRole
Update CustomerRelationship
Update Discount
Update DiscountType
Update Email
Update Equipment
Update Fax
Update Incident
Update IncidentResolution
Update Invoice
Update InvoiceDetail
Update KbArticle
Update KbArticleComment
Update KbArticleTemplate
Update Lead
Update Letter
Update List
Update Opportunity
Update OpportunityClose
Update OpportunityProduct
Update OrderClose
Update Organization
Update PhoneCall
Update PriceLevel
Update Product
Update ProductPriceLevel
Update Queue
Update Quote
Update QuoteClose
Update QuoteDetail
Update Role
Update SalesLiterature
Update SalesLiteratureItem
Update SalesOrder
Update SalesOrderDetail
Update Service
Update ServiceAppointment
Update Site
Update Subject
Update SystemUser
Update Task
Update Team
Update Template
Update Territory
Update TransactionCurrency
Update UoM
Update UoMSchedule
Update UserQuery
UploadFromBase64Data ActivityMimeAttachment
UploadFromBase64Data Annotation
UploadFromBase64Data SalesLiteratureItem
Win Opportunity
Win Quote

Enjoy,
Rami Heleg

How to get entity instance id in CRM 4.0 plugin for each message type

This example help to get instance id for each type of event:

Massage name “Create”:

Guid instanceID = new Guid(context.OutputParameters.Properties["id"].ToString());

Massage name “Update”:

Guid instanceID = (Guid)((Microsoft.Crm.Sdk.Key)((Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["Target"]).Properties[context.PrimaryEntityName + "id"]).Value;

Massage name “SetState”:

Guid instanceID = new Guid(context.OutputParameters.Properties["id"].ToString());

Massage name “Assign”:

Guid instanceID = vInstanceID = (Guid)((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

Massage name “Delete”:

instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

Massage name “Close”:

Guid instanceID = ((Microsoft.Crm.Sdk.Lookup)((Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["IncidentResolution"]).Properties[context.PrimaryEntityName + "id"]).Value;

Massage name “Route”:

Guid instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

Massage name “SetStateDynamicEntity”:

Guid instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["EntityMoniker"]).Id;


Enjoy,
Rami Heleg

Sunday, November 29, 2009

Allow to CRM 4.0 to pass( add) parameters to query string.

Hi,
CRM 4.0 disabled option to add parameters in query string.

to change this option need to change register.
goto Start - Run write -> regedit ( register)

Edit the registry in:
HKEY_Local_Machine\Software\Microsoft\MSCRM
Add a new DWORD
"DisableParameterFilter"
set value to 1.‬

this changes will help to add parameters in query string.

Enjoy,
Rami Heleg

Tuesday, November 17, 2009

Create Annotation with File

Here is an example to create Annotation:

annotation n = new annotation();

n.objectid = new Lookup();
//define to which entity
n.objectid.Value = new Guid(EntityId);
attach to specific entity
n.objecttypecode = new EntityNameReference();
n.objecttypecode.Value = EntityType;

//Create
Guid noteID = pService.Create(n);

//open and read file
FileInfo file = new FileInfo(fileP);
FileStream fs = file.OpenRead();
byte[] byteData = new byte[fs.Length];
fs.Read(byteData, 0, byteData.Length);
fs.Close();

string encodedData = System.Convert.ToBase64String(byteData);

//Create the Request Object
UploadFromBase64DataAnnotationRequest upload = new
UploadFromBase64DataAnnotationRequest();

//Set the Request Object's Properties
upload.AnnotationId = noteID;
upload.FileName = file.Name;
upload.MimeType = "text/plain";
upload.Base64Data = encodedData;

//Execute the Request
UploadFromBase64DataAnnotationResponse uploaded =
(UploadFromBase64DataAnnotationResponse)pService.Execute(upload);


Entity contain annotation + file.

enjoy,
Rami Heleg

Thursday, November 12, 2009

Use setInterval, clearInterval in CRM 3/4

Using setInterval if very helpful and powerfull when develop javascript in CRM 3/4.

Special target is to load forms very fast and make other code after user start to work.

This example contain two functions.
loadMyPage() and afterLoading()

function loadMyPage() call to function afterLoading() with interval of one second.

After second function afterLoading() is working..

Don’t forget to make the clearInterval.. clear calling.

function afterLoading() {
window.clearInterval(common_init_interval);
}

function loadMyPage(){
common_init_interval = setInterval('try { afterLoading (); } catch (e) { }', 1000);
}


Enjoy,
Rami Heleg

Handle Grid in IFRAME

Here is an example how to handle grid (like area grid) in IFRAME.

Add these 2 rows where form is loaded to get handle of the iframe


var iframe = document.getElementById('IFRAME_test');
iframe.onreadystatechange = FrameStateChanged;


function to handle iframe state changed like initalize, complete

function FrameStateChanged()
{
var iframe = document.getElementById('IFRAME_test');
if(iframe.readyState == "complete"){
// get grid from iframe
caseGrid = iframe.contentWindow.document.getElementById('crmGrid');
if (caseGrid != null)
caseGrid.attachEvent("onselectionchange",HandleGridSelectionChange);
}
}

// get guid from selected row.. can get all values.
function HandleGridSelectionChange()
{
//select row
var selectedRow = caseGrid.InnerGrid.SelectedRecords;
// get selected guid
if (selectedRow.length > 0)
var guid =selectedRow[0][0];

}


Enjoy,
Rami Heleg

Saturday, November 7, 2009

Replace tags to support legal JS page

The options to change string to be XML legal value:




Thanks,
Rami Heleg

Wednesday, November 4, 2009

Call from Javascript to Server via WCF/XML

Here is a simple example of calling to server from javascript side based WCF,XML

This example contain 3 options:
· Return string from server
· Return object from server
· Send object to server

1. create a new project name = ‘wcf2’

2. add new aspx page name Default.aspx.

3. paste code to javascript:






4. create new wcf service name 'Service.svc'

5. paste code the interface fileusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{
[OperationContract]
string GetsProperty1();
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/Person")]
Person GetDTO();

///
/// This is not working a real post. it still goes to the quesry string
///

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Person2?Property1={sProperty1}&Property2={nProperty2}&Property3={bProperty3}")]
Person GetDTO2(string sProperty1, int nProperty2, bool bProperty3);

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Person4?Property1={sProperty1}&Property2={nProperty2}&Property3={bProperty3}")]
Person GetDTO4(string sProperty1, int nProperty2, bool bProperty3);
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class Person
{
[DataMember]
public string sProperty1 = "123";

[DataMember]
public int nProperty2 = 123;

[DataMember]
public bool bProperty3 = true;

}

6. paste code to service fileusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Text;
using System.IO;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
private Person oPerson = new Person();

public string GetsProperty1()
{
return oPerson.sProperty1;
}
public Person GetDTO()
{
return this.oPerson;
}

public Person GetDTO2(string sProperty1, int nProperty2, bool bProperty3)
{
return this.oPerson;
}

public Person GetDTO4(string sProperty1, int nProperty2, bool bProperty3)
{
return this.oPerson;
}

public int GetDTO3(string sProperty1, int nProperty2, bool bProperty3)
{
return 590;
}
}
7. run project when default.aspx file is the startup page....
good luck,
Rami Heleg

Tuesday, November 3, 2009

Allow to Work with all CRM DB tables

Hi

I try to ask tables in CRM which I am not Authorized to ask.. what can I do?

You need to wrap the Query, Insert etc with this example


WindowsImpersonationContext impersonation = WindowsIdentity.Impersonate(IntPtr.Zero);
try {
// my code
} finally {
impersonation.Undo();
}

This solution will help you to work with all Database, CRM tables.

Enjoy,
Rami Heleg

How to get systemuser details in Plugin

Hi,
Here is an example how to get data in plugin code from server.
the example used to get info from systemuser table, but can be for every type of entity.


public static string GetUserFullName(IPluginExecutionContext context) {
try {
ICrmService service = context.CreateCrmService(false);
ColumnSetBase columns = new AllColumns();
systemuser oSystemUser = (systemuser)service.Retrieve("systemuser", context.UserId, columns);
return oSystemUser.fullname;
} catch (Exception ex) {
return ex.Message;
}


Enjoy,
Rami Heleg

Property ForceSubmit

CRM Send parameters from client to server only if IsDirty = true, it means fields has been changed.

this issue good for performance.
to send field value any way to server need to change field property like this example:
crmForm.all.firstname.ForceSubmit = true;

like that if field is disabled or contain the same value the value sent any way to server.

thanks,
Rami Heleg.

Saturday, October 31, 2009

Fetch Query



Fetch is an option to ask CRM information's.

To get information from CRM we can
1. Ask directly from DB
2. SDK for BE
3. Fetch.

To build fetch the best option is to build the fetch from Advanced find, see attached picture to get the fetch:
Write: javascript:alert(advFind.FetchXml)
Here are two examples to for query:

Sunday, October 11, 2009

How to pass information from steps 10 (pre) and post(50) in CRM Plug In

Here is an example how to pass information between pre and post ( 10- 50).

Object context contain SharedVariables.

Set values in 10 like this example code:
context.SharedVariables["myvalue"] = “rami Heleg”;

Read value in 50 ( post) like this example code:
string name = context.SharedVariables["status"].ToString();


Can be used for status win or Lose... or for closing incident and needs "IncidentResolution".

Thanks,
Rami Heleg

How to create CRM Plug In in CRM 4.0

1. Create a new project from type “class Library”

2. Create a new class with name : “MyExample”

3. Paste this code in new class.


using System;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

namespace MyExample{

public class AuditPlugin: IPlugin
{
public void Execute(IPluginExecutionContext context)
{
//start my code.
}
}
}

4. Compile and now the dll is ready to install with register tool.

Thanks,
Rami Heleg

Wednesday, October 7, 2009

Example of using XElement to create xml.

Hi,

Here is an example of using XElement to create xml.

The example is building xml, root, nodes and attributes.

The example is very very simple to make it in 2-3 rows

Requirement: Framework 3.5


using System.Xml.Linq;

example:

XElement element = new XElement("root");
element.Add(new XElement("MyNode",
new XAttribute("attr1", "value1"),
new XAttribute("attr2", "value2")));

element.Add(new XElement("MyNode2",
new XAttribute("attr1", "value3"),
new XAttribute("attr2", "value4")));
//xml is ready
element.ToString()

thanks
Rami Heleg,

Sunday, October 4, 2009

How to prevent SQL Timeout expired in Microsoft Dynamics CRM:

One of the problems when working with CRM and SQL is when making a complex Select/Query CRM get SQL time out.

The solution is define timeout in register.

1. Open regedit ( start - > write ( regedit) ) and press ok

2. Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM

3. Add DWORD name OLEDBTimeout with value 86400 ( 24 hours) select decimal

4. Add DWORD name ExtendedTimeout with value 1000000. The maximum value can be 2,147,483,647 and the default value is 30 seconds

This changes in register should fix the SQL timeout.

Thanks,
Rami Heleg.

Thursday, October 1, 2009

What is the property deletionstatecode ?

How can I remove from crm database record and not with delete command?

Each entity in CRM 4.0 includes two tables, base and extension.
In base table the columns are the same. statecode,guid,createdon...

One of the columns is deletationstatecode.

Deletionstatecode define if record is live in CRM or should be deleted.

Deletionstatecode = 0 record exist and live in CRM
Deletionstatecode = 2 record should e removed.

One of the services responsoble to remove all the record where deletionstatecode =2.
The if I need to remove many records in crm direct from database change the deletionstatecode to 2 and record will be removed after job finished.

Thanks,
Rami Heleg

Wednesday, September 30, 2009

Create log - first option in Event Viewer

Hi,

There are several options for writing logs

1. Create log in event viewer
2. Create log in file
3. Create log in entity log

Here is an example of writing log in event viewer


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace WriteToEventLog {
class Program {
static void Main(string[] args) {
string eventViewerName = "EventViewerName";
string sourceName = "Project name";
string message = "My Message";

if (!EventLog.SourceExists(sourceName))
EventLog.CreateEventSource(sourceName, eventViewerName);

EventLog.WriteEntry(sourceName, message);
EventLog.WriteEntry(sourceName, message, EventLogEntryType.Warning, 1100);
EventLog.WriteEntry(sourceName, message, EventLogEntryType.Error,45454);
}
}
}


Thanks
Rami Heleg.

Friday, September 25, 2009

Problem:
Running server-side code developments under CRM Server folder get Error 401 – Unauthorized.

This is a problem I've seen several times.
if you try to run the same code not under CRM folder and it works fine here is the Solution:

To solve this error need to make change in Microsoft CRM 4.0 web config:

What to add:










Thanks,
Rami Heleg

CRM Screens freeze- Stuck

Try to open CRM Form usually edit.aspx page with a few iframes.

in some cases screen Stuck.

The reason for that is internet explorer Settings.
The default connection for internet explorer is two. It means the main form request data + one of the iframes then other iframes wait.. this problem Causes CRM to be freeze.

Solution:
Change the default values:
Open register page:
1. Go to start - > run and Type regedit:
2. Define MaxConnectionsPer1_0Server and MaxConnectionsPerServer like the following example


[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings] MaxConnectionsPer1_0Server = dword: 0000000a
MaxConnectionsPerServer = dword: 0000000a





Thanks,

Rami Heleg

Tuesday, September 22, 2009

Update entity Based Micorost CRM SDK

Hi,
This example used to update record in crm 3.0 and crm 4.0 based SDK

//Create crm service
CrmService pService = new CrmService(); // optional to set url

// define entity + fields. mandatory field is key
incident oInc = new incident();
oInc.incidentid = new Key();
oInc.incidentid.Value = new Guid("guid");
oInc.title="my title"

pService.Update(oInc);

update Can get specific entity for instance contact, incident or dynamic entity.
all type of BusinessEntity.

thanks,
Rami Heleg

Monday, September 21, 2009

Create Entity Based Microsoft CRM SDK

Hi,
this example used to create a new record in crm 4,3 based CRM SDK.

//Create CRM Service
CrmService pService = new CrmService(); // optional to set url BusinessEntity

//Define entity and add values..
contact oContact = new contact();
oContact.firstname = "Rami";
oContact.lastname = "Heleg";

//Run method to create the entity.
Guid guid = pService.Create(entity);
//guid of the new record.


Thanks,
Rami Heleg

Using SDK to delete entity record via Dynamic entity

This Example help to delete record using SDK function.

DeleteRequest request = new DeleteRequest();
TargetDeleteDynamic target = new TargetDeleteDynamic();
target.EntityName = entityTypeName;
target.EntityId = instanceID;
request.Target = target;
pservice.Execute(request);

Enjoy,
Rami Heleg

RetrieveMultipleResponse - Query example.

Example of query on server side.

//Create Condition.. can be many conditions + type of operator
ConditionExpression[] conditions = new ConditionExpression[1];
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = fullname;
condition.Operator = ConditionOperator.Equal;
condition.Values = new object[] { "Rami Heleg" };
conditions[i] = condition;
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions = conditions;
QueryExpression query = new QueryExpression();

//Entity name
query.EntityName = "contact";

//allow to define specific columns
query.ColumnSet = new AllColumns();
query.Criteria = filter;
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.ReturnDynamicEntities = false;
request.Query= query ;
//run Query
RetrieveMultipleResponse response = (RetrieveMultipleResponse)pService.Execute(service, request);
//Result
response.BusinessEntityCollection.BusinessEntities;

Thanks,
Rami Heleg

Tuesday, September 15, 2009

View Schema via internet explorer

Hi,

Here is an example how to view schema information via internet explorer

http://servername:port/org_name/sdk/list.aspx

enable to view entities, attributes and relationships.

Thanks,
Rami Heleg

function to return on server side information regarding current system user.

Example of WhoAmI for Microsoft Dynamic CRM 4.0

CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "OrganizationName";

CrmService pService = new CrmService(); // optional to set url parameter
pService.CrmAuthenticationTokenValue = token;
pService.Credentials = CredentialCache.DefaultCredentials;

WhoAmIRequest request = new WhoAmIRequest();

WhoAmIResponse oSystem= (WhoAmIResponse)pService.Execute(request);
//oSystem.UserId;
//oSystem.OrganizationId ;//

Thanks,
Rami Heleg.

Monday, September 14, 2009

Example function to Set State for Dynamic entity

You can use Set State function for each entity for instance:
SetBusinessSystemUserRequest
SetAccountUserRequest
SetContactUserRequest and more.
Better is to create general function and use dynamic request
Example:
SetStateDynamicEntityRequest request = new SetStateDynamicEntityRequest();
request.Entity = new Moniker();
request.Entity.Name = entityTypeName;
request.Entity.Id = new Guid ( guid);
request.State = relevantStateCodeForSpecificEntity;
request.Status = relevantStatusForSpecificEntity;
service.Execute(request);

Enjoy,
Rami Heleg

Saturday, September 12, 2009

Change Maximum tabs

Hi,

CRM limit the number of tabs to 8.

To change the number:

C:\Program Files\Microsoft CRM Server\CRMWeb\Tools\FormEditor\formeditor.aspx

Need to change the parameter _iMaxTabs to required number.

Enjoy,
Rami Heleg

Shrink Javascript file

to improve performance one of the options is to shrink Javascript file.
link to site that help you to shrink the file and save 30 % from file size
http://www.creativyst.com/Prod/3/.

Recommended to do it before moving to production

Thanks,
Rami Heleg

Call from Javascript to Server via WCF/Json

Here is a simple example of calling to server from javascript side

1. create a new project name = 'WCFJson'
2. add new html page call HTMLPage.htm.
3. paste code to javascript:

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
var url = "http://localhost/WCFJson/Service.svc/rami/isExist";
var body = '{"name":"'+ "ramigggg" + '"}';
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState == 4){
alert( xmlHttp.responseText);
}
}

4. create new wcf service name 'Service.svc'
5. paste code the interface file


[ServiceContract]
public interface IService{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/isExist")]
bool isExist(string name);
}

6. paste code to service file


public class Service : IService
{
#region IService Members
public bool isExist(string name) {
return true;
}
#endregion
}

7. runproject when html file the the startup page....

good luck,
Rami Heleg

Attach event CRM Field

Here is an example to attach event to CRM Field

Function:

Function attachEvent (elementID, eventName, handler){
var obj =document.getElementById(elementID);
if (!element)
return;
element.attachEvent(eventName, handler);
}

Call Example:
attachEvent ('firstname’, 'onchange', handleFirstNameChanged);

Enjoy,
Rami Heleg

Set mandatory to CRM fields

Hi,
Here is the function to set mandatory to CRM field in Javascript

crmForm.SetFieldReqLevel(fieldName, value);

SetFieldReqLevel get 2 parameters

1. field name like firstname,createdon etc...
2. second parameter true,false.

Enjoy,
Rami Heleg

Thursday, September 10, 2009

Hot to get page name in crm,js

Hi,
Here is an example how to get page name.

function GetPageName() {
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
return sPage;
}

Rami Heleg,

Lookup Field properties

Hi,
here is the properties for lookup field in JS side

var parentIncident= new Array;
parentIncident = null;

parentIncident = crmForm.all.parentincident.DataValue;

if (parentIncident[0] != null)
{
//description
var desc = parentIncident[0].name;

//Guid
var incidentId = parentIncident[0].id;

// Object Type
var type = parentIncident[0].typename;

}

Enjoy,
Rami Heleg

crmForm, Field properties

Some words regarding field ( javascript side in crm)

to get field from crm page can by via two options:

1.
var firstName = crmForm.all.firstname;
2.
var firstName= document.getElementById('firstname'); //faster

properties + events:

1. firstName.SetFocus();
set focus on field.

2. firstName.IsDirty
true/false if field changed.

3. firstName.RequiredLevel
0 == normal
1 == recommended
2 == required

4. firstName.DataValue
set/get value from field.

5. firstName.ForceSubmit
send field value to server on save any way


Enjoy,
Rami Heleg.

crmForm Property

Here some words regarding crmForm properties

1. crmForm.IsDirty
if user change field in page IsDirty = true
2. crmForm.ObjectTypeName
return object name account,contact etc...
3. crmForm.ObjectTypeCode
return object key 1,2,112 etc.

Rami Heleg

crmForm FormType options

Hi,
this comment for form type - mode for edit page.

crmForm.FormType return form type/mode
1 = Create
2 = Update
3 = Read Only
4 = Disabled
5 = Quick Create
6 = Bulk edit ( After select multi records and choose from menu to create...


Rami Heleg,

Reading from webconfig/app config

Example how to read from web config

1. add using to page
using System.Configuration;Enjoy,
2. read from config file
string value= ConfigurationSettings.AppSettings["key"];

Enjoy,
Rami Heleg

Create Crm Service example based systemuser and organization

Here function to create Crm Service example for specific systemuser and organization name

public static CrmService GetCrmService(Guid callerID,string organizationName) {
CrmService rslt = new CrmService();
rslt.Url = "http://localhost:5555/MSCRMServices/2007/CrmService.asmx";
CrmServiceSdk.CrmAuthenticationToken token = new CrmServiceSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = organizationName;
token.CallerId = callerID;
rslt.CrmAuthenticationTokenValue = token;
rslt.Credentials =CredentialCache.DefaultCredentials;
return rslt;
}

Enjoy,
Rami Heleg

Create Metadata Service example

here function to create crmService based organization Name.

public static MetadataService GetMetadataService(string organizationName) {
MetadataService metadata = new MetadataService();
metadata.Url = "http://localhost:5555/MSCRMServices/2007/CrmService.asmx";
MetadataServiceSdk.CrmAuthenticationToken token = new MetadataServiceSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = organizationName;
metadata.CrmAuthenticationTokenValue = token;
metadata.Credentials =CredentialCache.DefaultCredentials;
return metadata;
}

Enjoy,
Rami heleg

Create CrmService example

here function to create crmService based organization Name.

public static CrmService GetCrmService(string organizationName) {
CrmService rslt = new CrmService();
rslt.Url = "http://localhost:5555/MSCRMServices/2007/CrmService.asmx";
CrmServiceSdk.CrmAuthenticationToken token = new CrmServiceSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = organizationName;
rslt.CrmAuthenticationTokenValue = token;
rslt.Credentials =CredentialCache.DefaultCredentials;
return rslt;
}

Enjoy,
Rami heleg

Set Value to Dynamic entity

Microsoft.Crm.Sdk.DynamicEntity entity

//Set value to CrmNumber
Microsoft.Crm.Sdk.CrmNumber number = new Microsoft.Crm.Sdk.CrmNumber();
number.Value = ToInt(propertyValue);
entity.Properties[propertyName] = number;

//Set Value to String
entity.Properties[propertyName] = propertyValue.ToString();


Enjoy,
Rami Heleg

Monday, September 7, 2009

SetMandatory

Hi,
Function to set mandtory true/false in CRM 4.0

this.setMandatory = function(fieldName, value) {
crmForm.SetFieldReqLevel(fieldName, value);
}

Enjoy,
Rami heleg

Friday, August 7, 2009

Function to get value from dyanamic entity field

public static Guid GetKeyValue(Microsoft.Crm.Sdk.DynamicEntity de, string val)
{
foreach (KeyProperty ent in de.Properties)
{
if (ent.Name == val)
return ent.Value.Value;
}
return Guid.Empty;

}

Enjoy,
Rami Heleg

Function to get value from dyanmic entity

public static string GetValueFromProperty(object property)
{
switch (property.GetType().Name)
{
case "String":
return ((String)property);
case "Lookup":
return ((Microsoft.Crm.Sdk.Lookup)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.Lookup)property).Value.ToString();
case "Picklist":
return ((Microsoft.Crm.Sdk.Picklist)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.Picklist)property).name.ToString();
case "Customer":
return ((Microsoft.Crm.Sdk.Customer)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.Customer)property).name.ToString();
case "CrmNumber":
return ((Microsoft.Crm.Sdk.CrmNumber)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.CrmNumber)property).Value.ToString();
case "CrmFloat":
return ((Microsoft.Crm.Sdk.CrmFloat)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.CrmFloat)property).Value.ToString();
case "CrmMoney":
return ((Microsoft.Crm.Sdk.CrmMoney)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.CrmMoney)property).Value.ToString();
case "CrmBoolean":
return ((Microsoft.Crm.Sdk.CrmBoolean)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.CrmBoolean)property).Value ? "1" : "0";
case "CrmDateTime":
return ((Microsoft.Crm.Sdk.CrmDateTime)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.CrmDateTime)property).Value;
case "Status":
return ((Microsoft.Crm.Sdk.Status)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.Status)property).Value.ToString();
case "State":
return "0";
case "Key":
return ((Microsoft.Crm.Sdk.Key)property).Value.ToString();
case "Owner":
return ((Microsoft.Crm.Sdk.Owner)property).IsNull == true ? "" : ((Microsoft.Crm.Sdk.Owner)property).name.ToString();
}
return "";
}

Enjoy,
Rami Heleg

Function to create CrmCustomer

public static Customer GetCrmCustomer(string entityTypeName, Guid value) {
Customer rslt = new Customer();
if (value == Guid.Empty)
rslt.IsNull = rslt.IsNullSpecified = true;
else {
rslt.type = entityTypeName;
rslt.Value = value;
}
return rslt;
}
Enjoy,
Rami Heleg

Function to create CrmPickList

public static Picklist GetCrmPicklist(int value) {
Picklist rslt = new Picklist();
if (value == 0)
rslt.IsNull = rslt.IsNullSpecified = true;
else
rslt.Value = value;
return rslt;
}
Enjoy,
Rami Heleg

Function to create CrmOwner

public static Owner GetCrmOwner(Guid ownerID) {
Owner rslt = new Owner();
if (ownerID == Guid.Empty)
rslt.IsNull = rslt.IsNullSpecified = true;
else {
rslt.Value = ownerID;
rslt.type = "systemuser";
}
return rslt;
}
Enjoy,
Rami Heleg

Function to create CrmStatus

public static Status GetCrmStatus(int value) {
Status rslt = new Status();
rslt.Value = value;
return rslt;
}

Enjoy,
Rami Heleg.

Function to create CrmMoney

public static CrmMoney GetCrmMoney(decimal value) {
CrmMoney rslt = new CrmMoney();
rslt.Value = value;
return rslt;
}
Enjoy,
Rami Heleg

Function to create CrmDecimal

public static CrmDecimal GetCrmDecimal(decimal value, bool isNull) {
CrmDecimal rslt = new CrmDecimal();
if (isNull)
rslt.IsNull = rslt.IsNullSpecified = true;
else
rslt.Value = value;
return rslt;
}

Enjoy,
Rami Heleg

Function to create CrmFloat

public static CrmFloat GetCrmFloat(float value, bool isNull) {
CrmFloat rslt = new CrmFloat();
if (isNull)
rslt.IsNull = rslt.IsNullSpecified = true;
else
rslt.Value = value;
return rslt;
}

Enjoy,
Rami Heleg

Function to create CrmBoolean

public static CrmBoolean GetCrmBoolean(bool value) {
CrmBoolean rslt = new CrmBoolean();
rslt.Value = value;
return rslt;
}
Enjoy,
Rami Heleg

Function to create crmdatetime

public static CrmDateTime GetCrmDateTime(DateTime value) {
CrmDateTime rslt = new CrmDateTime();
rslt.Value = value.ToString("yyyy-MM-ddTHH:mm:ss");
return rslt;
}

Enjoy
Rami Heleg

Wednesday, July 8, 2009

Get Attribute Picklist Value

An Example of getting picklist option label:

string entityTypeName = "contact";
string columnName= "new_sex";
string columnValue= "mail";
RetrieveAttributeRequest request = new RetrieveAttributeRequest();
request.EntityLogicalName = entityTypeName;
request.LogicalName = columnName;
RetrieveAttributeResponse response = (RetrieveAttributeResponse)metadataService.Execute(request);
PicklistAttributeMetadata attribute = (PicklistAttributeMetadata)response.AttributeMetadata;
for (int i = 0; i < attribute.Options.Length; i++)
if (attribute.Options[i].Value.Value == ConvertorUtils.ToInt(columnValue))
return attribute.Options[i].Label.ToString();
return "";
}
Enjoy,
Rami Heleg.

Get Entity Type Code - server side

Getting entity type code via metadata service
an Example for CRM 4.0

string entityTypeName = "contact";
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
request.MetadataItems = MetadataItems.EntitiesOnly;
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)metadataService.Execute(request);
CrmMetadata[] Metadata = response.CrmMetadata;
foreach (EntityMetadata meta in Metadata) {
if (meta.LogicalName == entityTypeName)
return meta.LogicalName;
}

Enjoy,
Rami Heleg

Get Entity Type Name - server side

Getting entity type name via metadata service
an Example for CRM 4.0

int entityTypeCode = 2;
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
request.MetadataItems = MetadataItems.EntitiesOnly;
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)metadataService.Execute(request);
CrmMetadata[] Metadata = response.CrmMetadata;
foreach (EntityMetadata meta in Metadata) {
if (meta.ObjectTypeCode.Value == entityTypeCode)
return meta.LogicalName;
}

Enjoy,
Rami Heleg

Saturday, July 4, 2009

Get Incident Details via Javascript

Hi,
here is an example to get incident details from server only from javascript side

function GetIncidentDetails(IncidentId) {
var xml = "" +
"" +
GenerateAuthenticationHeader() +
" " +
" " +
" " +
" " + "incident" + "" +
" " +
"
" +
" false" +
" " +
" And" +
" " + "incidentidEqual" + incidentId + "" +
"
" +
"
" +
"
" +
"
" +
"
" +
"";
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", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities");
return entityNode;
}

Enjoy,
Rami Heleg.

Get Contact Details from Javascript

function GetContactDetails(contactId) {
var xml = "" +
"" +
GenerateAuthenticationHeader() +
" " +
" " +
" " +
" " + "contact" + "" +
" " +
"
" +
" false" +
" " +
" And" +
" " + "contactidEqual" + contactId + "" +
"
" +
"
" +
"
" +
"
" +
"
" +
"";
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", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities");
return entityNode;
}

Hide buttons in menu bar

Hi,
Here is an example how to hide buttons in crm menu bar

function FideButton(buttonName){
var list = document.all.tags('SPAN');
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf('ms-crm-Menu-Label') >= 0)
if ((list[i].title == buttonName || list[i].innerText == buttonName))
list[i].style.display = 'none';
}
}

Enjoy,
Rami Heleg.

Friday, June 26, 2009

Get Field value

Here is an example to get field value in microsoft crm

function GetFieldValue(name) {
var element = document.getElementById(name);
return element == null ? null : element.DataValue;
}
Enjoy,
Rami Heleg

Get Field value

here is an example to get field value for microsoft CRM

Picklist - get title for value

Hi friends,
how to get picklist value,title

here example to create picklist title for specific value.

function GetPicklistTitle(name, value) {
if (value != '') {
var element = document.getElementById(name);
return element == null ? null : element.options[value].text;
}
return "";
}
enjoy
Rami Heleg.

Wednesday, June 24, 2009

Rename Organization name

Hi,
To rename organization name for CRM 4.0...
1. Open database MSCRM_CONFIG, table Organization.
2. This table contains information for all organization.
3. Rename columns UniqueName, FriendlyName to the new organization name.
3. Open ORG_MSCRM database table OrganizationBase.
4. Add to column name the new organization name.

Enjoy,
Rami Heleg.

Thursday, May 7, 2009

Return column label from plugin

this function used to return label for field.
can be used for plugin,audit etc...

public static string GetColumnLabel(IPluginExecutionContext context, string entityTypeName, string columnName)
{
IMetadataService metadataService = context.CreateMetadataService(false);
Microsoft.Crm.SdkTypeProxy.Metadata.RetrieveAttributeRequest request = new Microsoft.Crm.SdkTypeProxy.Metadata.RetrieveAttributeRequest();
request.EntityLogicalName = entityTypeName;
request.LogicalName = columnName.ToLower();
Microsoft.Crm.SdkTypeProxy.Metadata.RetrieveAttributeResponse response = (Microsoft.Crm.SdkTypeProxy.Metadata.RetrieveAttributeResponse)metadataService.Execute(request);
AttributeMetadata am = response.AttributeMetadata;
if (am != null)
return am.DisplayName.UserLocLabel.Label;
return "";
}

Enjoy,
Rami Heleg

Retrieve Entity field value

This function used to return field value inside plugin,

public static object GetEntityFieldValue(IPluginExecutionContext context,string entityName, Guid instanceId,string fieldName){
ICrmService pservice = context.CreateCrmService(false);
TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
targetRetrieve.EntityName = entityName;
targetRetrieve.EntityId = instanceId;
RetrieveRequest retrieve = new RetrieveRequest();
retrieve.Target = targetRetrieve;
retrieve.ColumnSet = new AllColumns();
retrieve.ReturnDynamicEntities = true;
RetrieveResponse retrieved = (RetrieveResponse)pservice.Execute(retrieve);
DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
return entity.Properties[fieldName];
}

Enjoy,
Rami Heleg

Tuesday, April 28, 2009

Retrieve entity and attributes via Javascript

This example used to get via Javascript information regarding entity + attributes


this.GetEntityAttrbiutes = function (entityName){
var xml = "" +
"" +
GenerateAuthenticationHeader() +
" " +
" "
+
" " +
" 00000000-0000-0000-0000-000000000000" +
" IncludeAttributes" +
" " + entityName+ "" +
" false" +
"
" +
"
" +
"
" +
"
" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/MetadataService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=windows-1255");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
return (resultXml);
}

Enjoy,
Rami Heleg

Retrieve Metadata for specific entity

this example uset to get via Javascript information regarding specific entity.
var xml = "" +
"" +
"" +
GenerateAuthenticationHeader() +
" " +
" "
+
" " +
" 00000000-0000-0000-0000-000000000000" +
" EntityOnly" +
" account" +
" false" +
"
" +
"
" +
"
" +
"
" +
"";

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

xmlHttpRequest.Open("POST", "/mscrmservices/2007/MetadataService.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;
alert(resultXml.xml);

Enjoy,
Rami Heleg

Sunday, April 26, 2009

RetrieveAllEntities in Javascript

How to get in Javascript all the information regarding entities,attribute and relation:

var xml = "" +
"" +
"" +
GenerateAuthenticationHeader() +
" " +
" " +
" " +
" All" +
"
" +
"
" +
"
" +
"
" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/MetadataService.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;
alert(resultXml.xml);


Enjoy,
Rami Heleg

Get Organization Name

Micrsoft Dyanamics CRM 4.0 contain constants with this parameter

parameter name is ORG_UNIQUE_NAME

:for instance display OrganizationName

alert(ORG_UNIQUE_NAME)



Enjoy,
Rami Heleg

WhoAmI - CRM 4.0

var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", http://schemas.microsoft.com/crm/2007/WebServices/Execute);
var soapBody = ""+
""+
""+
"
";
var soapXml = ""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'>";
soapXml += GenerateAuthenticationHeader();
soapXml += soapBody;
soapXml += "
";
xmlhttp.send(soapXml);
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xmlhttp.responseXML.xml);
var userid = xmlDoc.getElementsByTagName("UserId")[0].childNodes[0].nodeValue;
alert(userid);



Enjoy,
Rami Heleg