Calling Asp.NET web service from javascript (Ajax)

Here we will be calling the default helloworld webservice that is already created for us when we open a asp.net 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”);

xmlHttp.open(“post”, “http://localhost/WebService1/Service1.asmx/HelloWorld&#8221;, false);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.send();

return false;

}

function doUpdate()

{

if(xmlHttp.readyState==4)

{

var startTag = “<string xmlns=\”http://tempuri.org/\”>”;

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);

document.forms[0].elements[‘Info’].value=exch;

}

</script>

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

if(window.ActiveXObject)

{

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

}

else if (window.XmlHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

xmlHttp.open(“post”, “http://localhost/WebService1/Service1.asmx/HelloWorld&#8221;, 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

xmlHttp.onreadystatechange=doUpdate;

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

xmlHttp.send();

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.

if(xmlHttp.readyState==4)

It tells about the current state of the request

0- uninitialized

1- loading

2- loaded

3-interactive

4-complete

xmlHttp.responseXML.xml

It returns the current response from server in XML=

<?xml version=”1.0″?>

<string xmlns=”http://tempuri.org/”>Hello World !</string>

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

document.forms[0].elements[‘Info’].value=exch;

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()

{

if(xmlHttp.readyState==4)

{

// 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;

document.forms[0].elements[‘Info’].value=respText;

}

 

However creating a ASP.NET AJAX webservice is little different than our normal ASP.NET web service, and calling them using the ASP.NET AJAX client library is also a bit different

https://nishantrana.wordpress.com/2007/11/06/creating-and-calling-aspnet-ajax-web-service/

Bye

Advertisements

Refresh CRM form from third-party applications

http://support.microsoft.com/default.aspx/kb/821669

Code to put in the javascript of our custom page

function window.onunload()
{
window.opener.location.reload();
window.close();
}

But the thing with the code is that it only works when we deploy the page in the same server where our Crm is deployed.

When i had deployed the page in my machine, the page wasn’t refreshing but when i deployed the same page where the crm is deployed everything was working perfectly fine.

I think in the previous case because of the cross-domain issue i guess there were problems.

One more thing,  to assign values to attributes in our Crm Form from our isv page we can make use of familiar syntax

window.opener.document.crmForm.all.new_totalbilling.DataValue=parseInt(//value );

parseInt – if the crm attribute is of numeric type

alert(window.parent.document.all.crmForm.all.name.DataValue);

Bye

Finding shared records in CRM

To find all the records(say lead)  shared with any particular user we can make use of following query

It will return us all records(lead) shared with the user directly( i.e. through Action–>Sharing and user)

select  fl.subject

from
PrincipalObjectAccess poa , FilteredLead fl, FilteredSystemUser fsu
where
poa.ObjectTypeCode = 4
and poa.ObjectId = fl.leadid
and poa.PrincipalId = fsu.systemuserid
and fsu.domainname=SYSTEM_USER

// fsu.fullname=’name of user’

And to get the records shared with the user indirectly (i.e. through Action–>Sharing and Team (user belongs to that team)

select  fl.subject
from 
FilteredLead fl,  PrincipalObjectAccess poa,  FilteredTeam ft
where
poa.ObjectTypeCode = 4 

and poa.ObjectId =fl.leadid
and poa.PrincipalId = ft.teamid and 

fl.owneridname not in (select fullname from filteredsystemuser
where domainname=SYSTEM_USER)
and
ft.teamid  in (select ft.teamid from filteredteammembership fm
, filteredsystemuser fsu, filteredteam ft
where fm.systemuserid=fsu.systemuserid and
ft.teamid=fm.teamid
and fsu.domainname=SYSTEM_USER
)

Bye

Making value in one lookup depended on value of another lookup.

Making value in one lookup depended on value of another lookup in Microsoft CRM. Say we have created 2 custom entities Categories and Skill. Skill entity has category lookup field which relates it to that category.(Added a relationship between them)Than created few records for both the entities. After that we have added that entities to the third entity where they’ll appear as LookUp.

Now we want the value of Skill lookup to be dependent value selected on Resource(Category) LookUp.

untitled1.JPG

Resource can have following values

untitled2.JPG

Now if Datawarehousing is selected than

we want to show Analysis and SSAS in the Skill lookup

untitled3.JPG

To accomplish this we will write the following code in the OnChange event of Resource Lookup

// Making the skill id lookup null whenver a new values is selected for reesource

crmForm.all.new_skillid.DataValue=null;

crmForm.all.new_skillid.disabled = false;

// getting the value of selected resource

var ar=new Array();

ar=crmForm.all.new_resourceid.DataValue;

var rID = ar[0].id;

// Changing the display of skillid lookup so that only skill belonging to particular rID should appear

crmForm.all.new_skillid.lookupbrowse=1;

// in the additionalparams for the skill id attribute we will specify the fetch xml query // e.g. select * from new_categoryskill (name of our custom skill entity) where new_categoryofskillid = rid

crmForm.all.new_skillid.additionalparams = “fetchXml=<fetch mapping=’logical’ ><entity name=’new_categoryskill’><all-attributes/><filter type=’and’><condition attribute=’new_categoryofskillid’ operator=’eq’ value='” + rID + “‘/></filter></entity></fetch>”;

To get the fetchXml query what we can do over here is

http://ronaldlemmen.blogspot.com/2006/11/using-advanced-find-for-fetchxml.html

We will go to our skill entity form and run an advancedfind query against it (giving the appropriate condition for which we want the fetch xml)

Now pressing CTRL+N open it in a new window Now in URl replace everything with the following line

javascript:prompt(“my%20query:”,%20resultRender.FetchXml.value);

Press Ok to the dialog that appears and it opens a prompt window from where we can copy our fetch xml and modify it accordingly.


Using Left and CharIndex in Oracle

Well i was given the task to get the email id’s of the user which was stored in one of our oracle db table.

But the problem was that we wanted that part of emailid which  appears before ‘@’ .

Well coming from SQL Server background i thought it could be acheived using CharIndex and Left Function.

Let’s see what they do

Select Left(‘abcdef’,3)

-> abc

and

select charindex(‘c’,’abcde’)

-> 3

But than as expected there were no functions like charindex and left in Oracle.

After searching i finally managed to found the solution

Inplace of CharIndex we have instr function

select instr(‘ab’,’b’) from dual;

->2

and for left and also right we have

SUBSTR (`ABCDEF’,-5); //Right(..)

SUBSTR (`ABCDEF’,1,5); // Left(…

So finally the query was

substr(emailid,1,Instr(Emailid,’@’)-1)

-1 is used otherwise @ will also come along

And one more thing, to extract username portion from login name i.e  nishantr1 from

abccompany\nishantr1 we could write something as following

SUBSTRING(loginname ,charindex(‘\’,loginname)+1, len(loginname)) for sql server.


Bye

Using ISV.config to access field values in CRM

First of all open your isv.config file ( found at <installation path\_Resources\isv.config e.g. C:\Program Files\Microsoft CRM\CRMWeb\_Resources”

Here we are adding buttons in the form toolbar for opportunity, inside the isv.config file (Plzz take it’s backup)

Add the following

<Entity name=”opportunity”>

<ToolBar ValidForCreate=”0″ ValidForUpdate=”1″>

<Button Title=”MyBtn1″ Icon=”/_imgs/ico_18_debug.gif”

Url=”http://default.aspx” PassParams=”1″ WinParams=”” WinMode=”0″ AvailableOffline=”false” />

<Button Title=”my button” ToolTip=”Advanced Mail Merge” Icon=”url” Client=”Web, Outlook”

JavaScript=

var n=crmForm.all.name.DataValue;

var objectID=crmForm.ObjectId;

window.open(‘http://Default.aspx?name=’+n+’&oId=’+objectID)”

/>

</ToolBar>

</Entity>

In the above code we have created two button.

First button makes use of URL and passParam attribute.

When we set passParam as 1 then objectid( id of the record), object name and object type code are passed to url specified as query string.

The thing here is that in our custom web page we can only get the id and the type of entity.

What if we want values of other form fields.

Well in this case we can make use of JavaScript attribute.This attribute will override the Url attribute if in case both of them are defined.In the above code we are attaching the name value of opportunity in the query string.

One more thing to get the current record’s primary key i.e. say opportunity id for opportunity we’ll use crmForm.ObjectId

We can even user window.opener object in javascript of our isv custom page.

Chk this

https://nishantrana.wordpress.com/2007/10/13/refresh-crm-form-from-third-party-applications/

Bye

Finding Lead records that have an associated activity with them

Here in the query one more condition is added which is when the Rating is Hot. 

select leadqualitycodename,* from filteredlead As fl inner join dbo.FilteredActivityParty as fap
ON fl.leadid=fap.partyid
and fl.leadid=‘yourleadid’ and leadqualitycodename=‘Hot’ 

Events in C#

We’ll take a simple and useful scenario to make our understanding of Events as clear as possible.
First of all copy and paste the code below. We’ll try understanding the code than.

using System;
public class ResultDeclarationEventArgs : EventArgs
{
private string message;
public ResultDeclarationEventArgs(string message)
{
this.message = message;
}
public string Messsage
{
get
{
return message;
}
}
}
public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
public class Kid
{
private int percentage;
public event ResultHandler onResultDeclaration;
public int Percentage
{
set
{
percentage = value;
if(percentage > 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs( ” I got Distinction”);
onResultDeclaration(this, myREA);
}
if(percentage > 60 && percentage < 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got FirstClass”);
onResultDeclaration(this, myREA);
}
if(percentage > 40 && percentage < 60)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got SecondClass”);
onResultDeclaration(this, myREA);
}
if(percentage < 40)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” Sorry I failed “);
onResultDeclaration(this, myREA);
}
}
}
}
public class Mom
{
public Mom(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToMom);
}
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

public class Dad
{
public Dad(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
}
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

class myDemo
{
public static void Main()
{
Kid kid = new Kid();
Mom mom = new Mom(kid);
Dad dad = new Dad(kid);
Console.WriteLine(“Please enter the percentage of the Kid”);
string percentage = Console.ReadLine();
kid.Percentage = Convert.ToInt32(percentage);
}
}

The scenario is something like this First there is a class named Kid. It has a field called Percentage and declares an event OnResultDeclaration. It is of type ResultHandler. ResultHandler is a delegate. public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
It can point or refer to any method which has return type void and takes as parameter an object and ResultDeclarationEventArgs.
Object will give the name of the sender who has called this eventhandler and ResultDeclarationEventArgs is to pass any information regarding the event.

ResultDeclarationEventArgs is a class that derives from EventArgs class. It has a message field which will contain the message the Kid class, which has the event OnResultDeclaration, would like to convey to the class (e.g. Mom, Dad) which are interested in that event.
For this reason, we have our event handlers(method) inside Mom and Dad class which have the same signature as defined by the event.
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
Than we register these eventHandler to the events.
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);

Kid class will check for the percentage passed in and accordingly set’s the message.
Whatever message is set is than displayed in the Event handler inside Mom and Dad class using e.Message

Understading Delegates

What are delegates?
Delegates are object that refer to an method. Normally we refer to objects, however referring to an object isn’t any different from referring a method they too have physical location in memory.

Why use delegate?
One delegate can be used to call different methods during runtime of a program by simply changing the method to which the delegate refers.
and Delegates Support Events.

delegate ret-type name(paramerter-list);
e.g. delegate string MyDelegate();

The MyDelegate can call any method whose return type is string and accepts no parameter. It can be instance method or a static method.

delegate string MyDelegate(String s);
class Program
{
static string GetNameLower(String s)
{
return s.ToLower() ;
}
static string GetNameUpper(string s)
{
return s.ToUpper();
}
static void Main(string[] args)
{
MyDelegate myD = new MyDelegate(GetNameLower); //or myD=GetNameLower
string s1 = myD(“Hi Nishant”);
Console.WriteLine(s1);
myD = new MyDelegate(GetNameUpper); //or myD=GetNameUpper
string s2 = myD(“Hi Nishant”);
Console.WriteLine(s2);
}
}

Understanding Multicasting

We can have chain of methods that will be called automatically when a delegate is invoked.
For this we will use += operator to add methods to chain and -= to remvove a method.
If delegate returns value than value returned by the last method becomes the return value of entire deleagation invocation. Thus a delegate making use of multicasting will have void as return type.

delegate void MyDelegate();
class Program
{
static void GetNameLower()
{
Console.WriteLine(“GetNameLower Called”);
}
static void GetNameUpper()
{
Console.WriteLine(“GetNameUpper Called”);
}
static void Main(string[] args)
{
MyDelegate myD = GetNameLower;
myD +=GetNameUpper;
myD(); //invoking the delegate
}

Understanding Static keyword in C#

Static keyword can be applied to
Class, field, method, properties, operator, event and constructors.
Static member belongs to the class and not to any object of the class.
They can be used without creating the instance of the class.

For e.g. Static Void Main()
It is called by the operating system on program execution
To access the static member we’ll use

ClassName.staticmember

When a variable is declared as static internally what happens is that all the instances of the class share the same static variable. A static variable is initialized when its class is loaded. If not
initialized explicitly then
it is initialized to zero for numeric variable
null in case of object references
false for boolean

StaticMethod they can only contain static member and call other static method.
If we need to access them than it can be done through the object of that class

class Game
{
string getGameName()
{
……………….
}
public static void getNameThroughStatic(Game g)
{
g.getGameName(); // accessing static method
}
}

When to use them?
Well we can use them when we need to maintain information applicable to the entire class

suppose we have a class Employees there we can have a static count variable to keep track of no of employees.

class Employees
{
static in count=0;
public Employees()
{
count++;
}

~Employees
{
count–;
}

}

What are Static Constructor?
They can be used to initialize the static variables.
They are called automatically and before the instance constructor (if called any).

for above class
static Employees() // no other access modifiers for them
{}

What are static Classes?
A class whose objects can’t be created and which can only have static members. They can’t be inherited as well.
They can have static constructor

Why use static Classes?
It can be used to group related static method.