Using FilteredView to retrieve data in Plug-In or Callout

To retrieve data from CRM Database( FilteredView)…..

SqlConnection connection = new SqlConnection(“DataSource=<dsName>;Initial Catalog=<databaseName> ;Integrated Security=SSPI;”);

string sqlQuery = @” select max(new_uniqueid) from FilteredView” ;

SqlCommand cmd = new SqlCommand(sqlQuery, connection);



/// Write Logic here




But this code wasn’t returning any results .It was because callout/plugin run under the context of NT Authority\Network Service.

So we need to use impersonation in this case, for this we can use the following code .

SqlConnection connection = new SqlConnection(“DataSource=<dsName>;Initial Catalog=<databaseName> ;Integrated Security=SSPI; Pooling=false);

string sqlQuery = @” SETUSER ‘domainName\administrator’ select max(new_uniqueid) from FilteredView” ;

SqlCommand cmd = new SqlCommand(sqlQuery, connection);



/// Write Logic here




SETUSER To impersonate the admin who has access to the filtered views. More about SETUSER

If we are not using Pooling=false in connection string its giving this error.

Event Log Error: The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context…….


DynamicEntity Overview

A Dynamic Entity consists of a collection of strongly typed properties, much like a Property Bag. Dynamic Entities are used to develop against CRM entities and attributes that are not defined at design time.

When to use Dynamic Entities


Use the DynamicEntity class when writing code that must work on entities created after the code is deployed or with attributes added to entities after deployment


Example for accessing the accountid attribute using DynamicEntity.




The reason for the Value.Value is because dynEntity [“accountid”].value returns a Property object whose Value property points to the CRM Attribute type which in our case is Key. Key stores the GUID in its Value property.


Example of Using DynamicEntity for Create,Retrieve,Update,Delete.


Create DynamicEntity


DynamicEntity de = new DynamicEntity(“contact”);

StringProperty propFirstName = new StringProperty(“firstname”, “Arvind”);


StringProperty propLastName = new StringProperty(“lastname”, “Singh”);


m_ID = Service.Create(de);


Retrieving a DynamicEntity


RetrieveRequest req = new RetrieveRequest();

req.ColumnSet = new AllColumns();

req.ReturnDynamicEntities = true;

TargetRetrieveDynamic target = new TargetRetrieveDynamic();

target.EntityName = “contact”;

target.EntityId = m_ID;

req.Target = target;

RetrieveResponse resp = (RetrieveResponse)service.Execute(req);

DynamicEntity de = (DynamicEntity)resp.BusinessEntity;

Key id = (Key)de.Properties[“contactid”] ;

string firstName = de.Properties[“firstname”].ToString();

string lastName = de.Properties[“lastname”].ToString();


Update using DynamicEntity


DynamicEntity de = new DynamicEntity(“contact”);

Key key = new Key(m_ID);

KeyProperty keyProp = new KeyProperty(“contactid”, key);


StringProperty propFirstName = new StringProperty(“firstname”, “John”);


StringProperty propLastName = new StringProperty(“lastname”, “Smith”);






Service.Delete(“contact”, m_ID);


How to get CRM Server Url from ISV.Config or OnLoad Event of Form

finding crm server url from ISV.Config

write a function as

getUrl= function() {
                                return url;


CRM Customization Import failed Error: Invalid name prefix

While importing the customization from development(upgraded from 3.0 to crm 4.0) to QA Server(fresh installation CRM 4.0) i was getting this error: “Import failed: opportunity_new_dataaudit: Invalid name prefix.” 

It was giving the error on particular relationship: “opportunity_new_dataaudit”

I solved this problem as open the customization.xml in edit mode its look like as

<EntityRelationship Name=”Opportunity_New_DataAudit“>
<Description description=”Unique identifier for Opportunity associated with Data Audit.” languagecode=”1033″ />
<field name=”new_opportunityid” requiredlevel=”none” imemode=”auto” lookupstyle=”single” lookupbrowse=”0″>
<displayname description=”Opportunity” languagecode=”1033″ />


<AttributeMaps />

We solved this problem intrestingly, we change the name property of tag <EntityRelatioship> from opportunity_new_dataaudit



<EntityRelationship Name=”new_Opportunity_New_DataAudit“>

i.e simply appending prefix new_ to the relationship name in customization.xml. It imported successfully now..

How to Call Web Service from Java Script

Here we will be calling the default helloworld webservice that is already created for us when we open a webservice project template in Visual Studio.

We’ll just have a textbox(html control) which will display us the Hello World! response returned from the web service.

This is the step we need to follow

1) Create a new ASP.NET WebApplication

2) Put a html textbox control on the form

<input type=”text” id=”info”/>

3) Put this script code in the head section of the aspx page

<script language=”javascript”>

var xmlHttp;

function getMessage()


xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);”post”, “http://localhost/WebService1/Service1.asmx/HelloWorld”, false);



return false;


function doUpdate()




var startTag = “<string xmlns=\”\”>”;

var endTag = “</string>”;

var exch;

var valueStart = 0;

var valueEnd = 0;

valueStart = xmlHttp.responseXML.xml.indexOf(startTag, valueEnd) + startTag.length;

valueEnd = xmlHttp.responseXml.xml.indexOf(endTag, valueEnd+1);

exch = xmlHttp.responseXML.xml.substring(valueStart, valueEnd);





4) Call the getMessage function in the body’s onLoad eventHandler

<BODY onload=”getMessage()”>

5) Run the applicaton. We’ll see the HelloWorld! text in our textbox(’info’)

Now let us understand what is happening inside the javascript code

xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”)

This line of code creates the XMLHttpRequest object. This object sends request to the server and processes the responses from it.

The above code creates the object specific to Internet Explorer( <=6.o).

It is implemented as Active X for IE. However in IE 7 XMLHttpRequest will come as native JavaScript object.

For other browsers we can write

xmlHttp=new XMLHttpRequest();

or best we can write this



xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);


else if (window.XmlHttpRequest)


xmlHttp=new XMLHttpRequest();

}”post”, “http://localhost/WebService1/Service1.asmx/HelloWorld”, false);

The open method initializes the connection to the server and informs the xmlHttp object how to connect to the server.

post- it indicates how we want to send the data. It can be “get” as well

url- comes the url where we are connecting

false- this means we are making a synchronous call. To make asychronous call simply set it to true


This specifies the name of the function to be called whenever the state of the xmlHttpRequest changes


Send method than makes the request to server. This method would return immediately in case of asynchronous call and it would block until the synchronous response is received from the server.


It tells about the current state of the request

0- uninitialized

1- loading

2- loaded




It returns the current response from server in XML=

<?xml version=”1.0″?>

<string xmlns=””>Hello World !</string>

Than we are using some javascript functions to get the Hello World! and remove everything else.


Finally assigning the value to our textBox.

The function doUpdate() can be written differently so that we don’t have to make use of any string functions.

function doUpdate()




// Here the server is returning us XML in response so we can make use of responseXML

// Here the browser creates a DOM tree to represent that XML and puts a reference to that DOM tree

// in the request’s (xmlHttp) object’s responseXML

var xmlDoc=xmlHttp.responseXML;

var responseElement=xmlDoc.getElementsByTagName(”string”)[0];

var respText=responseElement.firstChild.nodeValue;



%d bloggers like this: