SendEmail Message

Sends an e-mail message.



//# The following code shows how to use the SendEmail message.

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create a SendEmail request.
SendEmailRequest req = new SendEmailRequest();
req.EmailId = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
req.TrackingToken = "";
req.IssueSend = true;

// Send the e-mail message.
SendEmailResponse res = (SendEmailResponse)service.Execute(req);




Get Record Guid by name

//Change the fetch query as per use
 
/* Jscript */


document.getBuGuid = function(product_nm){
//var _d_fxml = "";
var _d_fxml = "<fetch mapping='logical'><entity name='new_businessinterest'><no-attrs/><filter type='and'><condition attribute='new_name' operator='eq' value='"+product_nm+"'/></filter></entity></fetch>";
//var _e_fxml = CrmEncodeDecode.CrmHtmlEncode(_d_fxml);
var soap_header= document.genSoap(_d_fxml);
var ajResponse = document.ajaxSoap(soap_header);

var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM"); //Create an XML document that you can parse.o
oXmlDoc.async = false;

oXmlDoc.loadXML(ajResponse); //Load the XML document that has the UnEncoded results.
var results = oXmlDoc.getElementsByTagName('resultset');
var bu_guid = oXmlDoc.selectNodes("//new_businessinterestid")[0].text;
var re1='.*?'; // Non-greedy match on filler
var re2='([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})'; // SQL GUID 1
var p = new RegExp(re1+re2,["i"]);
var m = p.exec(bu_guid);
if (m != null)
{
var guid1=m[1];
return(guid1.replace(/ }
};

Impersonation in Plug-ins

Impersonation is used to execute business logic (code) on behalf of a Microsoft Dynamics CRM system user to provide a desired feature or service for that user. Microsoft Dynamics CRM obtains the pre-entity and post-entity images that are passed to plug-ins in the execution context on behalf of the impersonated system user. Any business logic executed within a plug-in, including Web service method calls, is governed by the security privileges of the impersonated user.

Plug-ins execute under the security account, which is specified on the Identity tab of the CRMAppPool Properties dialog box. The dialog box can be accessed by right-clicking the CRMAppPool application pool in Internet Information Services (IIS) Manager and then clicking Properties in the shortcut menu. By default,CRMAppPool uses the Network Service account identity. If the CRMAppPool identity is changed to a system account other than Network Service, the new identity account must be added to the PrivUserGroup group in Active Directory.

The two methods that can be employed to impersonate a user are discussed in the next two topics.

Impersonation during plug-in registration

One method to impersonate a system user within a plug-in is by specifying the impersonated user during plug-in registration. When registering a plug-in, if theimpersonatinguserid field of the sdkmessageprocessingstep or SdkMessageProcessingStepRegistration class instance is set to a specific Microsoft Dynamics CRM system user, Web service calls made by the plug-in execute on behalf of the impersonated user. If the impersonatinguserid field is set to a value of null orGuid.Empty during plug-in registration, the calling/logged on user or the standard "system" user is the impersonated user.

Whether the calling/logged on user or "system" user is used for impersonation is dependent on the request being processed by the pipeline and is beyond the scope of the SDK documentation. For more information about the "system" user, refer to the next topic.

Impersonation during plug-in execution

Impersonation that was defined during plug-in registration can be altered in a plug-in at run time. Even if impersonation was not defined at plug-in registration, plug-in code can still use impersonation. The following discussion identifies the key properties and methods that play a role in impersonation when making Web service method calls in a plug-in.

The platform passes the impersonated user ID to a plug-in at run time through the IPluginExecutionContext.UserId property. The UserId property can have one of three different values as shown in the table below.

UserId Value
Condition

Initiating user

or

"system" user

The impersonatinguserid property of the sdkmessageprocessingstep or SdkMessageProcessingStepRegistration class instance is set to null orGuid.Empty at plug-in registration.

Impersonated user
The impersonatinguserid property is set to a valid system user ID at plug-in registration.

"system" user
The current pipeline was executed by the platform, not in direct response to a Web service method call.

If you specify an impersonated user during plug-in registration, you should set up the Web service proxy in the plug-in by passing a value of true to theCreateCrmService method or the CreateMetadataService method. Passing a value of true indicates to use the ID in the IPluginExecutionContext.UserId property as the impersonated user. The following code example shows how to do this.

Example

[C#] ICrmService service = context.CreateCrmService(true);

This is equivalent to the following code:

Example

[C#] ICrmService service = context.CreateCrmService(context.UserId);

To ignore any impersonating user set during plug-in registration, use the following code.

Example

[C#] ICrmService service = context.CreateCrmService(false);

When a value of false is passed to the CreateCrmService method or the CreateMetadataService method, the platform uses the built-in "system" account to execute Web service method calls made by your plug-in code. The "system" account is a high privilege user account with some restrictions. For example, the "system" account cannot create a task activity.

The InitiatingUserId property of IPluginExecutionContext contains the ID of the system user that called the Web service method that ultimately caused the plug-in to execute. The following code shows how to create a Web service proxy to make Web method calls on behalf of the initiating user.

Example

[C#] ICrmService service = context.CreateCrmService(context.InitiatingUserId);

If the impersonatinguserid property is set during plug-in registration, this line of code effectively ignores that setting for any Web method calls to the Web service.

For plug-ins executing offline, any entities created by the plug-in are owned by the logged on user. Impersonation in plug-ins is not supported while in offline mode.

Note   When you register a plug-in by using the plug-in registration sample tools that are provided with the SDK, Web service methods invoked by the plug-in always execute under the account of the calling or logged on user. The tools do not offer impersonation as a supported feature. For more information about the tool sample code, see Sample Code.

CRM 4.0 Videos with John-ODonnell

: Installation

: Report Wizard

: Data Migration Manager

: Workflow and Processes

: Advanced Find

: Import Data Wizard

: Duplicate Detection

: Security

: Multicurrency

: Multi-Tenancy

Hide show and select tabs in CRM 4.0

How to hide, show and select tabs in CRM 4.0 If you already worked with Microsoft Dyamics CRM 4.0, you know that almost everything you do with JavaScript is considered a "hack" because you manipulate the DOM of the pages by yourself. Because of this I decided to give you some help with differents helper methods I developped at my day job. I'm currently working on a big development project involving CRM.

Hide a tab in CRM 4.0

 
/* Jscript: Hide a tab in CRM 4.0 */




function HideTab(tabNumber)
{
var tab = document.getElementById("tab" + (tabNumber - 1).toString() + "Tab");
tab.style.display = "none";
}

Show a tab in CRM 4.0

 
/* Jscript: Show a tab in CRM 4.0 */
function ShowTab(tabNumber)
{
var tab = document.getElementById("tab" + (tabNumber - 1).toString() + "Tab");
tab.style.display = "";
}

Select a tab in CRM 4.0

 
/* Jscript: Select a tab in CRM 4.0 */
function SelectTab(tabNumber)
{
var tab = document.getElementById("tab" + (tabNumber - 1).toString() + "Tab");
tab.click();
}

Using CrmDiscoveryService

Type Value Description
AD 0 Specifies Active Directory authentication.
Passport 1 Specifies Windows Live ID authentication.
Spla 2 Specifies Internet-Facing Deployment authentication

1. Active Directory authentication.Sample code
 

try{

String username = "domain\\user";
String password = "password";
String authType = "AD";
String OrganizationName = "orgName";
String hostBame = "http://xxx.xxx.x.xxx";
String CrmDiscoveryURL = hostBame + "/MSCRMServices/2007/"+ authType + "/CrmDiscoveryService.asmx";


CrmDiscoveryURL = CrmDiscoveryURL.toLowerCase();

CrmDiscoveryServiceLocator discoveryServiceLoc = new CrmDiscoveryServiceLocator();
discoveryServiceLoc.setCrmDiscoveryServiceSoapEndpointAddress(CrmDiscoveryURL);
CrmDiscoveryService discoveryService = (CrmDiscoveryService) discoveryServiceLoc;
CrmDiscoveryServiceSoapStub discoveryServiceSoap = (CrmDiscoveryServiceSoapStub) discoveryService.getCrmDiscoveryServiceSoap();


discoveryServiceSoap.setUsername(username);
discoveryServiceSoap.setPassword(password);

RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
orgRequest.setUserId(username);
orgRequest.setPassword(password);
RetrieveOrganizationsResponse orgResp = (RetrieveOrganizationsResponse) discoveryServiceSoap.execute(orgRequest);

OrganizationDetail orgInfo = null;
com.microsoft.schemas.crm._2007.CrmDiscoveryService.ArrayOfOrganizationDetail arrayOfDetail= orgResp.getOrganizationDetails();
OrganizationDetail[] orgdetails = arrayOfDetail.getOrganizationDetail();


for (int i = 0; i < orgdetails.length; i++) {


System.out.println("orgdetails[i].getOrganizationName() = "+ orgdetails[i].getOrganizationName());
if (orgdetails[i].getOrganizationName().equalsIgnoreCase(OrganizationName)) {

orgInfo = orgdetails[i];
break;
}
}

int AD = 0;
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.setAuthenticationType(AD);
token.setOrganizationName(OrganizationName);


String CrmServiceUrl = orgInfo.getCrmServiceUrl();




CrmServiceSoapStub adminBinding = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL(CrmServiceUrl));

adminBinding.setHeader("http://schemas.microsoft.com/crm/2007/WebServices","CrmAuthenticationToken", token);

adminBinding.setUsername(username);
adminBinding.setPassword(password);

WhoAmIRequest whoRequest = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse) adminBinding.execute(whoRequest);

String UserId = whoResp.getUserId();

System.out.println("userid = "+ UserId);

}catch(Exception e){
e.printStackTrace();
}





2. Passport Authentication
Sample code
 
String authType = "Passport";
CrmDiscoveryServiceLocator discoveryServiceLoc = new CrmDiscoveryServiceLocator();
discoveryServiceLoc.setCrmDiscoveryServiceSoapEndpointAddress("http://" + hostName + "/MSCRMServices/2007/" + authType + "/CrmDiscoveryService.asmx");

CrmDiscoveryService discoveryService = (CrmDiscoveryService) discoveryServiceLoc;
CrmDiscoveryServiceSoapStub discoveryServiceSoap = (CrmDiscoveryServiceSoapStub) discoveryService.getCrmDiscoveryServiceSoap();

// Retrieve Policy Request
RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
RetrievePolicyResponse policyResponse = (RetrievePolicyResponse) discoveryServiceSoap.execute(policyRequest);

String passportTicket = getPassportTicket(policyResponse.getPolicy(),userName, password);

RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
crmTicketRequest.setOrganizationName(organization);
crmTicketRequest.setPassportTicket(passportTicket);
crmTicketResponse = (RetrieveCrmTicketResponse) discoveryServiceSoap.execute(crmTicketRequest);

if (crmTicketResponse != null) {

CrmAuthenticationToken token = new CrmAuthenticationToken();
int PASSPORT = 1;
token.setAuthenticationType(PASSPORT);
token.setCallerId("00000000-0000-0000-0000-000000000000");
token.setOrganizationName(crmTicketResponse.getOrganizationDetail().getOrganizationName());
token.setCrmTicket(crmTicketResponse.getCrmTicket());
String crmServiceUrl = crmTicketResponse.getOrganizationDetail().getCrmServiceUrl();// we can store it in db w.r.t user,pass,org and retrieve
CrmServiceSoapStub crmServiceSoapStub = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL(crmServiceUrl));


crmServiceSoapStub.setHeader("http://schemas.microsoft.com/crm/2007/WebServices","CrmAuthenticationToken", token);

WhoAmIRequest whoRequest = new WhoAmIRequest();
whoRequest.setOptionalParameters(new OptionalParameter[] {});

WhoAmIResponse whoResp = (WhoAmIResponse) crmServiceSoapStub.execute(whoRequest);
System.out.println("----------getUserId()----------------->"+ whoResp.getOrganizationId());
}

private String getPassportTicket(String policy, String userName, String password) {

String ticket= null;


try{

String passportDomain = "crm.dynamics.com";//partner
String environment = "Production";
ticket = new MSLogonManager().logon(userName, password, passportDomain, policy, environment);
System.out.println("ticket = "+ticket);

}catch(Exception e){

e.printStackTrace();
}
return ticket;
}







3. IFD Authentication




String hostBame = "https://xx.xxxx.xxx";
String OrganizationName = "orgName";
String username = "usernam";
String password = "password";

String CrmDiscoveryURL = hostBame+"/mscrmservices/2007/spla/crmdiscoveryservice.asmx";

CrmDiscoveryServiceLocator discoveryServiceLoc = new CrmDiscoveryServiceLocator();
discoveryServiceLoc.setCrmDiscoveryServiceSoapEndpointAddress(CrmDiscoveryURL);
CrmDiscoveryService discoveryService = (CrmDiscoveryService) discoveryServiceLoc;
CrmDiscoveryServiceSoapStub discoveryServiceSoap = (CrmDiscoveryServiceSoapStub) discoveryService.getCrmDiscoveryServiceSoap();

discoveryServiceSoap.setUsername(username);
discoveryServiceSoap.setPassword(password);

RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
orgRequest.setUserId(username);
orgRequest.setPassword(password);
RetrieveOrganizationsResponse orgResp = (RetrieveOrganizationsResponse) discoveryServiceSoap.execute(orgRequest);

OrganizationDetail orgInfo = null;
com.microsoft.schemas.crm._2007.CrmDiscoveryService.ArrayOfOrganizationDetail arrayOfDetail = orgResp.getOrganizationDetails();
OrganizationDetail[] orgdetails = arrayOfDetail.getOrganizationDetail();


for (int i = 0; i < orgdetails.length; i++) {

System.out.println(" getIFDBindingToCrm orgdetails[i].getOrganizationName() "+ orgdetails[i].getOrganizationName());

if (orgdetails[i].getOrganizationName().equalsIgnoreCase(OrganizationName)) {

orgInfo = orgdetails[i];
break;
}
}

RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
crmTicketRequest.setOrganizationName(OrganizationName);//orgInfo.getOrganizationName());
crmTicketRequest.setUserId(username);
crmTicketRequest.setPassword(password);
RetrieveCrmTicketResponse crmTicketResponse = (RetrieveCrmTicketResponse) discoveryServiceSoap.execute(crmTicketRequest);

if (crmTicketResponse != null) {//

int IFD = 2;
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.setAuthenticationType(IFD);
token.setOrganizationName(orgInfo.getOrganizationName());
token.setCrmTicket(crmTicketResponse.getCrmTicket());

String CrmServiceUrl = orgInfo.getCrmServiceUrl();
System.out.println("CrmServiceUrl-" + CrmServiceUrl);

CrmServiceSoapStub adminBinding = (CrmServiceSoapStub) new CrmServiceLocator().getCrmServiceSoap(new URL(CrmServiceUrl));

adminBinding.setHeader("http://schemas.microsoft.com/crm/2007/WebServices","CrmAuthenticationToken", token);

adminBinding.setUsername(username);
adminBinding.setPassword(password);

WhoAmIRequest whoRequest = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse) adminBinding.execute(whoRequest);
String UserId = whoResp.getUserId();

System.out.println("UserId="+UserId);
}






LookupProperty in a plugin

 

This is the code to create a lookup property for my custom entity

Lookup salesPersonLookup = new Lookup(“new_salesperson”, crmkey.Value);
LookupProperty lookupProperty = new LookupProperty(“new_salespersonid”, salesPersonLookup);

first you need to create a lookup, this has the syntax of

new Lookup(“entity name”, guid of entity to lookup) 

then you need to add the lookup into a LookupProperty

new LookupProperty(“field name”, Lookup) 

You then add this property to your property bag and you will be able to update that property

Create a SharePoint Website from a CRM Plug-in



using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using MyCrmService = ProfessionalServicesPlugins.CrmSdk;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace ProfessionalServicesPlugins
{
public class CreateProjectPlugin : IPlugin
{
///
/// Provision a SharePoint web when new Projects are created
///

public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;

// Create the task on the Microsoft CRM server.
MyCrmService.CrmService crmService = GetCrmService();

// Check if the input parameters property bag contains a target
// of type DynamicEntity and it is the correct entity type
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity &&
context.PrimaryEntityName == MyCrmService.EntityName.new_project.ToString())
{
// Obtain the target business entity from the input parmameters
entity = (DynamicEntity)context.InputParameters.Properties["Target"];

// Get the Project CRM properties
string projectName = entity.Properties["new_name"].ToString();

// Because plug-ins run as Network Service,
// we need to run with elevated
// privileges within SharePoint
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Access the root site collection
using (SPSite elevatedSite = new
SPSite("http://localhost:7777/sites/projects"))
{
SPWebCollection sites = elevatedSite.AllWebs;
elevatedSite.AllowUnsafeUpdates = true;

// Create the new Web
using (SPWeb web = sites.Add(projectName, projectName,
projectName, 1033, "STS#0", false, false))
{
// Add the URL to the entity
entity.Properties.Add(new StringProperty("new_sharepointurl",
web.Url));
}
}
});
}
}

private MyCrmService.CrmService GetCrmService()
{
// Setup the Authentication Token
MyCrmService.CrmAuthenticationToken token = new
MyCrmService.CrmAuthenticationToken();
token.OrganizationName = "MicrosoftCRM";

MyCrmService.CrmService crmService = new MyCrmService.CrmService();
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
crmService.CrmAuthenticationTokenValue = token;

return crmService;
}
}
}





AJAX wrapper

JavaScript AJAX wrapper for Ajax calls
 
/* Jscript */


//// AJAX wrap
function AjaxWrapper()
{
var object = this;

object.Request = NewRequest();
object.Request.onreadystatechange = CompleteRequest;

this.Sync = true;
this.Method = "GET";
this.URL = "";
this.WebServiceMethod = "";
this.Parameters = new ParameterCollection();

this.Execute = ExecuteRequest;
this.AsyncCallbackMethod = null;

this.ResultXML = null;
this.ResultText = null;

function NewRequest()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else
return new ActiveXObject("Microsoft.XMLHTTP");
}

function ExecuteRequest()
{
var parameters = object.Parameters.toString();

ResetRequest();

if (this.Method.toUpperCase() == "POST")
{
if (object.WebServiceMethod.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod, !object.Sync);
else
object.Request.open(object.Method, object.URL, !object.Sync);

object.Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
object.Request.send(object.Parameters);
}
else if (this.Method.toUpperCase() == "GET")
{
if (object.WebServiceMethod.length > 0 && parameters.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod + "?" + parameters, !object.Sync);
else if (object.WebServiceMethod.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod, !object.Sync);
else if (parametres.length > 0)
object.Request.open(object.Method, object.URL + "?" + parameters, !object.Sync);
else
object.Request.open(object.Method, object.URL, !object.Sync);

object.Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
object.Request.send();
}
else
{
throw "The method '" + this.Method.toUpperCase() + "' is not supported !";
}

if (object.Sync)
FinishRequest(object.Request.responseText);
}

function CompleteRequest()
{
if (object.Request.readyState == 4)
{
if (object.Request.status == 200)
{
FinishRequest(object.Request.responseText);

if (object.AsyncCallbackMethod != null)
object.AsyncCallbackMethod();
}
}
}

function ResetRequest()
{
object.Request = NewRequest();
object.Request.onreadystatechange = CompleteRequest;
}

function FinishRequest(retourTexte)
{
var xmlDoc = new ActiveXObject("MSXML2.DOMDocument");

object.ResultText = object.Request.responseText;

try
{
xmlDoc.loadXML(object.Request.responseText);

if (xmlDoc.parsed && xmlDoc.xml.length > 0)
object.ResultXML = xmlDoc;
else
object.ResultXML = null;
}
catch (ex)
{
object.ResultXML = null;
}
}
}

Installation guide for CRM 4.0 / Step by Step guide to install CRM 4.0

Complete Installation guide for CRM 4.0 / Step by Step guide to install CRM 4.0

        Last week I installed Microsoft Dynamic 4.0 on my virtual machine and I found that it will be helpful for beginner like me, if there is a step by step installation guide. Lets start with OS selection.

1. You can use Windows Server 2003 or later server version. I had Windows Server 2003 R2.

2. Install latest service pack for OS you installed.

3. Install Internet Information Service.

4. Install Active Directory.

5. Configure DNS Server.

6. Create new user for domain and make him member of Administrators group.

7. Install SQL Server 2005 with Reporting Service and Analysis service.

8. Configure new account as service account for Report Server and Analysis server.

9. Install Visual Studio 2008.

10. Start installation of CRM 4.0

11. Enter display name for your Organization.

clip_image001

12. Next step is to select installation path, you can leave this as it is or select specific folder,

clip_image002

13. Next select website for CRM, I choose new website with different port address in my case it was 5555 as shown in image below,

clip_image003

14. Next you need to enter URL for Reporting server.

15. Next you have to select Organization Unit. Click on Browse button and select the root node of your domain in my case it is chirag.

clip_image004

16. On next step you need to specify security account, choose the one you created in step 6. Enter the password in password textbox and click next.

17. Select your local machine as Email Router setting or select specific machine on domain which you are using at email server. I chose my local machine so localhost.

18. Once you click next you will see System Requirements screen. If Domain user, SQL Server Reporting Service and ASP.NET are installed properly you will receive no error or warning else you will receive error message. I received following errors,

clip_image005

19. If you receive error message for SQL Server or SQL Server Reporting Service don’t be afraid. Open Services from Start – All Programs – Administrative Tools – Services. Check whether SQL Server Agent is running. If not right click on service and select property. Select Startup Type as Automatic and click on start button.

20. Another common error is for Indexing service. Follow the steps mention in point 19 to start Indexing Service.

21. You can see a warning mentioning Verify Domain User account SPN for the Microsoft Dynamics CRM ASP.NET Application Pool account. This will usually shows when you add specific domain account for security account in step 16. You can solve this warning now or after installation.

22. If System Requirements screen show no error or warning on next step installation will be started.

23. Finally you will see following screen, this means your CRM is installed.

clip_image006

RetrieveMultiple Message

Retrieves a collection of business entity instances of a specified type based on query criteria.



//# The following code examples show how to use the RetrieveMultiple message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the column set that indicates the fields to be retrieved.
ColumnSet cols = new ColumnSet();

// Set the properties of the column set.
cols.Attributes = new string [] {"name", "accountid"};

// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();

// Set the condition for the retrieval to be when the city in the account's address is Sammamish.
condition.AttributeName = "address1_city";
condition.Operator = ConditionOperator.Like;
condition.Values = new string [] {"Sammamish"};

// Create the FilterExpression.
FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions = new ConditionExpression[] {condition};

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = EntityName.account.ToString();
query.ColumnSet = cols;
query.Criteria = filter;

// Create the request object.
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

// Set the properties of the request object.
retrieve.Query = query;

// Execute the request.
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);




CRM 2011 Plugins

Plugins - Introduction


Plugins - Registration & Diagnostics

Parsing XML Content

 
/* Jscript: Parse XML Document */


var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM"); //Create an XML document that you can parse.
oXmlDoc.async = false;
oXmlDoc.loadXML(resultSet); //Load the XML document that has the UnEncoded results.
var results = oXmlDoc.getElementsByTagName('result'); //get the specified node by DOM function
var currency = oXmlDoc.selectNodes("//businessinterest")[1].text; //gets the no of nodes with function



Using Generics in CRM 4

Generics can be used to simplify the CRM Web Service method calls.

account acc = CrmSystem.Retrieve(myAccountId);




Here is one of the overloads for the Retrive Method that uses Generics, it calls an other overload that does the actual call to CRM Web Service using the EntityName string that we get thru typeof(T).Name

public T Retrieve(Guid id, params string[] columnSet) where T : BusinessEntity { 
return (T)Retrieve(typeof(T).Name, id, new ColumnSet(columnSet));
}

Get FetchXml as DataSet


private DataSet FetchDataSet(string fetchXml){
string strResult = service.Fetch(fetchXml);
DataSet ds = new DataSet();
System.IO.StringReader reader = new System.IO.StringReader(strResult);
ds.ReadXml(reader);
return ds;
}