Handling SOAP Exceptions In Microsoft Dynamics CRM


The only exception thrown by the CRM Web service is a common

SoapException whose message property is always “Server was unable to process

request.”

 

To handle that exception, catch the exception and display the InnerXml error

code, error text, and error description

 

Example

 

try

{

// Delete the non-existent Contact

service.Delete(EntityName.contact.ToString(), contactGuid);

}

catch (SoapException ex)

{

// This will contain the error message from the platform

Console.WriteLine(“Microsoft Dynamics CRM Error

Information:”);

Console.WriteLine(ex.Detail.InnerText);

// The InnerXml contains the details of the error in a

parsable XML format

XmlDocument error = new XmlDocument();

error.LoadXml(ex.Detail.InnerXml);

// Render out the details of the error

Console.WriteLine(“Error Code: ” +

error.SelectSingleNode(“/error/code”).InnerText);

Console.WriteLine(“Error Description: ” +

error.SelectSingleNode(“/error/description”).InnerText);

Console.WriteLine(“Error Type: ” +

error.SelectSingleNode(“/error/type”).InnerText);

}

 

 

Using the RetrieveMultiple Method in Microsoft Dynamics CRM 4.0


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the ColumnSet indicating the properties to be

retrieved

ColumnSet cols = new ColumnSet();

// Sets the ColumnSet’s Properties

cols.Attributes = new string [] {“fullname”, “contactid”};

// Create the ConditionExpression

ConditionExpression condition = new ConditionExpression();

// Set the Condition for the Retrieval to be when the

contact’s address’ city is Sammamish

condition.AttributeName =”address1_city”;

condition.Operator = ConditionOperator.Like;

condition.Values = new string [] {“Sammamish”};

// Create the FilterExpression

FilterExpression filter = new FilterExpression();

// Set the Filter’s Properties

filter.FilterOperator = LogicalOperator.And;

filter.Conditions = new ConditionExpression[] {condition};

// Create the QueryExpression Object

QueryExpression query = new QueryExpression();

// Set the QueryExpression Object’s Properties

query.EntityName = EntityName.contact.ToString();

query.ColumnSet = cols;

query.Criteria = filter;

// Retrieve the Contacts

BusinessEntityCollection contacts =

service.RetrieveMultiple(query);

 

Using Update Method of CrmService WebService


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the contact object.

contact contact = new contact();

// Set the contact object properties to be updated.

contact.address1_line1 =”34 Market St.”;

// The contactid is a key that references the ID of the

contact to be updated.

contact.contactid = new Key();

// The contactid.Value is the GUID of the record to be

changed.

contact.contactid.Value = new Guid(“4D507FFE-ED25-447B-

80DE-00AE3EB18B84″);

// Update the contact.

service.Update(contact);

Using Create Method of CrmService WebService


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the column set object that indicates the

properties to be retrieved.

ColumnSet cols = new ColumnSet();

// Set the properties of the column set.

cols.Attributes = new string [] {“fullname”};

// contactGuid is the GUID of the record being retrieved.

Guid contactGuid = new Guid(“4D507FFE-ED25-447B-80DE-

00AE3EB18B84″);

// Retrieve the contact.

// The EntityName indicates the EntityType of the object

being retrieved.

contact contact =

(contact)service.Retrieve(EntityName.contact.ToString(),

contactGuid, cols);

 

Using the CrmDiscoveryService Web Service In CRM4.0: On-Premise


CrmDiscovery service is a global installable level service that allow the caller to determine the correct organization and URL for his/her need.

Below example show how to create and configure CrmDiscoveryService Web Service proxy.

 

// Create and configure the CrmDiscoveryService Web service

proxy.

CrmDiscoveryService discoveryService = new

CrmDiscoveryService();

discoveryService.UseDefaultCredentials = true;

discoveryService.Url

=”http://localhost/MSCRMServices/2007/AD/CrmDiscoveryServic

e.asmx”;

// Retrieve the list of organizations that the logged on

user belongs to.

RetrieveOrganizationsRequest orgRequest = new

RetrieveOrganizationsRequest();

RetrieveOrganizationsResponse orgResponse =

(RetrieveOrganizationsResponse)discoveryService.Execute(org

Request);

// Locate the target organization in the list.

OrganizationDetail orgInfo = null;

foreach (OrganizationDetail orgDetail in

orgResponse.OrganizationDetails)

{

if

(orgDetail.OrganizationName.Equals(“AdventureWorksCycle”))

{

orgInfo = orgDetail;

break;

}

}

// Check whether a matching organization was not found.

if (orgInfo == null)

throw new Exception(“The specified organization was not

found.”);

 

Creating AutoNumber for Microsoft Dynamics CRM 4.0 using Plug-Ins with the help of FilteredView


Create two field as we created..

1) New_uniqueid ( Int)

2) New_id( nvarchar).

If you want AutoNumber as Int , no need to create two fields ,but we wanted AutoNumber as in specific format(OP/DEC08/0000000001) so we reqired to two field.

Steps for AutoNumber:

1) Retrieved the maximum number for entity based on field new_uniqueid.

2) Update both field new_uniqueid and new_id using web service on PostCreate event.

Source Code

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.Xml.Serialization;

using System.IO;

using System.Collections;

using Microsoft.Crm.Sdk;

using System.Data;

using System.Data.SqlClient;

using System.Web.Services.Protocols;

namespace CRM.PlugIn.UniqueIdGeneration

{

public class PlugInForUniqueId : IPlugin

{

string serverName = string.Empty;

string domain = string.Empty;

string authUser = string.Empty;

int leftPad;

string uniqueNoField=string.Empty;

string uniqueIdField=string.Empty;

static string logPath = string.Empty;

// get configuration string

public PlugInForUniqueId(string unsecure, string secureConfiguration)

{

XmlDataDocument doc = new XmlDataDocument();

doc.LoadXml(secureConfiguration);

// get database server name

XmlNode database = doc.SelectSingleNode(“//Database”);

serverName= database.InnerText;

// get domain name

XmlNode domainName = doc.SelectSingleNode(“//Domain”);

domain = domainName.InnerText;

// CRM User as Authentication User

XmlNode authUserName = doc.SelectSingleNode(“//AuthUser”);

authUser = authUserName.InnerText;

// get total no of digit for padding

XmlNode padding = doc.SelectSingleNode(“//Padding”);

leftPad=Convert.ToInt32( padding.InnerText);

// get FieldName and type of datatype should be Integer

XmlNode uniqueNo = doc.SelectSingleNode(“//UniqueNumber”);

uniqueNoField= uniqueNo.InnerText;

// get FieldName and type of datatype should be nvarchar

XmlNode Id = doc.SelectSingleNode(“//Id”);

uniqueIdField= Id.InnerText;

// get path of log file.

XmlNode Log = doc.SelectSingleNode(“//LogPath”);

logPath = Log.InnerText;

}

public void Execute(IPluginExecutionContext context)

{

// Create instance of Crm WenService

ICrmService Service = context.CreateCrmService(true);

string entityName = context.PrimaryEntityName;

string orgName = context.OrganizationName;

// Avialable max. number in database.

int maxUniqueNo = ReturnMaxNumber(serverName, entityName, orgName);

CrmNumber num = new CrmNumber();

num.Value = maxUniqueNo;

// Formatted Unique Id With entityname,month,year and unique No.

string formattedId = FormattedUniqueNumber(num.Value, context.PrimaryEntityName);

try

{

// DynamicEntity dyEntity = ReturnDynamicEntityToUpate(context, num);

if (context.InputParameters.Properties.Contains(“Target”))

{

DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties[“Target”];

if (entity != null)

{

string entityId = context.PrimaryEntityName + “id”;

Guid id = (Guid)context.OutputParameters[ParameterName.Id];

DynamicEntity updateUniqueId = new DynamicEntity(context.PrimaryEntityName);

Key key = new Key(id);

KeyProperty keyProp = new KeyProperty(entityId, key);

updateUniqueId.Properties.Add(keyProp);

CrmNumberProperty propUniqueId = new CrmNumberProperty(uniqueNoField, num);

updateUniqueId.Properties.Add(propUniqueId);

StringProperty propFormattedId = new StringProperty(uniqueIdField, formattedId);

updateUniqueId.Properties.Add(propFormattedId);

Service.Update(updateUniqueId);

}

}

}

catch (SoapException SoapEx)

{

WriteLog(entityName, “On Create”,“ERROR”,SoapEx);

}

catch (Exception ex)

{

WriteLog(entityName, “On Create”, “ERROR”, ex.Message);

}

}

private int ReturnMaxNumber(string server, string entity, string orgName)

{

int maxNum = 0;

string dataSource = server;

string tableView = “Filtered” + entity;

string organizatioName = orgName ;

string databaseName = organizatioName + “_MSCRM”;

string sqlQuery = @” SETUSER ‘”+domain +“\\”+ authUser + “‘ select max(new_uniqueid) from “ + tableView ;

WriteLog(entity , “On Create”, “INFO”, “DatabaseServer :” + dataSource);

WriteLog(entity, “On Create”, “INFO”, “Sql Query :” + sqlQuery);

try

{

SqlConnection connection = new SqlConnection(“Data Source=” + dataSource + “;Initial Catalog=” + databaseName + “;Integrated Security=SSPI; Pooling=false”);

SqlCommand cmd = new SqlCommand(sqlQuery, connection);

connection.Open();

if (cmd.ExecuteScalar().ToString() != “”)

{

maxNum = Convert.ToInt32(cmd.ExecuteScalar());

}

connection.Close();

connection.Dispose();

if (maxNum > 0)

{

maxNum++;

}

else

{

maxNum = 1;

}

}

catch (SqlException sqlex)

{

WriteLog(entity, “On Create”, “ERROR”, sqlex);

maxNum =0;

}

return maxNum;

}

private string FormattedUniqueNumber(int num, string entity)

{

string finalUniqueNo=string.Empty;

try

{

DateTime currentDate = DateTime.Now;

string getMonth = currentDate.ToString(“MMM”).ToUpper();

string getYear = currentDate.Year.ToString().Substring(2, 2);

string numWithPad = num.ToString().PadLeft(leftPad, ‘0’);

string entiyName = entity.Substring(0, 2).ToUpper();

finalUniqueNo = entiyName + “/” + getMonth + getYear + “/” + numWithPad;

WriteLog(entity, “On Create”, “INFO”, “Unique ID=” + finalUniqueNo);

return finalUniqueNo;

}

catch (Exception ex)

{

WriteLog(entity, “On Create”, “ERROR”, ex.Message);

return finalUniqueNo;

}

}

private static void WriteLog(string Entity, string EventName, string MessageType, SoapException ex)

{

try

{

string lstrMessage;

TextWriter log = TextWriter.Synchronized(File.AppendText(logPath));

lstrMessage = Entity + ” | “ + EventName + ” | “ + MessageType + ” | “ + System.DateTime.Now.ToString () + ” | “ + ex.Detail.InnerXml;

log.WriteLine(lstrMessage);

log.Close();

}

catch (Exception ex1)

{

throw ex1;

}

}

private static void WriteLog(string Entity, string EventName, string MessageType, string Message)

{

try

{

string lstrMessage;

TextWriter log = TextWriter.Synchronized(File.AppendText(logPath));

lstrMessage = Entity + ” | “ + EventName + ” | “ + MessageType + ” | “ + System.DateTime.Now.ToString () + ” | “ + Message ;

log.WriteLine(lstrMessage );

log.Close();

}

catch (Exception ex)

{

throw ex;

}

}

private static void WriteLog(string Entity, string EventName, string MessageType, SqlException Message)

{

try

{

string lstrMessage;

TextWriter log = TextWriter.Synchronized(File.AppendText(logPath));

lstrMessage = Entity + ” | “ + EventName + ” | “ + MessageType + ” | “ + System.DateTime.Now.ToString() + ” | “ + Message ;

log.WriteLine(lstrMessage);

log.Close();

}

catch (Exception ex)

{

throw ex;

}

}

}

}

Now Register the Plug-In for any entity on PostCreate event.It will give the AutoNuber in this format(OP/DEC08/0000000001) I.e (first two character of Entity name/three character of current month+ two digit of current year/number with padding(10 digit but customizable))

Don’t forget to pass configuration string when registering Plug-In in Secure Configuration Field in this format

<Config><Database>Machine Name of Database</Database><Domain>Domain Name</Domain><AuthUser>Authenticated User of CRM on behalf of that query will be executed</AuthUser><Padding>number of character for padding </Padding><UniqueNumber>new_uniqueid</UniqueNumber><Id>new_id</Id><LogPath> Log path as D:\CRM\Logs\CrmLog.txt</LogPath></Config>