Moving CRM Servers(Application and Database) to New DataCentre


One of our client wanted to move CRM Server from One Data Centre to different data centre but due to some constraint we could not move it by creating New Organization or by new deployment. We had only left option was update IP address manually.

Recently we moved our CRM Server from one data centre to new data centre due to which IP Address of both Application and Database Server was changed. We had updated new IP Address in Registry(MSCRMconfigdb,database,LocalSdkHost,metabase,ServerUrl,SQLRSServerUrl), Application Pool, Web.Config and custom application. But even after updating new IP address on above section  we were getting the following error.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.23.201.162:80

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.23.201.162:80

Source Error:

An unhandled exception was generated during the execution   of the current web request. Information regarding the origin and location of   the exception can be identified using the exception stack trace below.

Stack Trace:

 
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.23.201.194:80]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
   System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224

[WebException: Unable to connect to the remote server]
   System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +1868309
   System.Net.HttpWebRequest.GetRequestStream() +13
   System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
   Microsoft.Crm.Metadata.MetadataWebService.GetDataSet() +31
   Microsoft.Crm.Metadata.DynamicMetadataCacheLoader.LoadDataSetFromWebService(Guid orgId) +291
   Microsoft.Crm.Metadata.DynamicMetadataCacheLoader.LoadCacheFromWebService(LoadMasks masks, Guid organizationId) +42
   Microsoft.Crm.Metadata.DynamicMetadataCacheFactory.LoadMetadataCache(LoadMethod method, CacheType type, IOrganizationContext context) +408
   Microsoft.Crm.Metadata.MetadataCache.LoadCache(IOrganizationContext context) +339
   Microsoft.Crm.Metadata.MetadataCache.GetInstance(IOrganizationContext context) +388
   Microsoft.Crm.BusinessEntities.BusinessEntityMoniker..ctor(Guid id, String entityName, Guid organizationId) +116
   Microsoft.Crm.Caching.UserDataCacheLoader.LoadCacheData(Guid key, ExecutionContext context) +323
   Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key, IOrganizationContext context) +401
   Microsoft.Crm.Caching.BasicCrmCache`2.CreateEntry(TKey key, IOrganizationContext context) +84
   Microsoft.Crm.Caching.BasicCrmCache`2.LookupEntry(TKey key, IOrganizationContext context) +135
   Microsoft.Crm.BusinessEntities.SecurityLibrary.GetUserInfoInternal(WindowsIdentity identity, IOrganizationContext context, UserAuth& userInfo) +252
   Microsoft.Crm.BusinessEntities.SecurityLibrary.GetCallerAndBusinessGuidsFromThread(WindowsIdentity identity, Guid organizationId) +179
   Microsoft.Crm.Authentication.CrmWindowsIdentity..ctor(WindowsIdentity innerIdentity, Boolean publishCrmUser, Guid organizationId) +252
   Microsoft.Crm.Authentication.WindowAuthenticationProviderBase.Authenticate(HttpApplication application) +431
   Microsoft.Crm.Authentication.AuthenticationStep.Authenticate(HttpApplication application) +172
   Microsoft.Crm.Authentication.AuthenticationPipeline.Authenticate(HttpApplication application) +86
   Microsoft.Crm.Authentication.AuthenticationEngine.Execute(Object sender, EventArgs e) +525
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

 

Actually It was still referring Old IP Address at some places. To resolve the issue we enable the trace log and get CrmServerReportInformation with help of “Create File” option of  CrmDiagTool 4.0  and came to know that DeploymentProperty Table(Column Name- ADSdkRootDomain, ADWebApplicationRootDomain and AsyncSdkRootDomain) of MSCRM_Config was still referring old IP Address. We have updated this column with new IP Address as below and everything start working fine.

USE MSCRM_CONFIG

Update DeploymentProperties SET NVarCharColumn = ‘New IP Address’  WHERE ColumnName= ‘AsyncSdkRootDomain’

Update DeploymentProperties SET NvarCharColumn = ‘New IP Address’  WHERE ColumnName = ‘ADSdkRootDomain’

Update DeploymentProperties SET NvarCharColumn = ‘New IP Address’  WHERE ColumnName = ‘ADWebApplicationRootDomain’

 

Hope this help you 🙂

Send Email using Template


public void SendMail(ICrmService service,Guid ownerID, Guid fromGuid, ArrayList toGuid,Guid recordRegardingID,Guid templateId,Enum  enitityName)
{

// Create an instance of email
email myEmail = new email();
//set the owner of the mail
myEmail.ownerid = new Owner();
myEmail.ownerid.type = EntityName.systemuser.ToString();
myEmail.ownerid.Value = ownerID;
// specify the from part of the email
activityparty from = new activityparty();
from.partyid = new Lookup();
from.partyid.type = EntityName.systemuser.ToString();
// guid of the system user who is sending the mail
from.partyid.Value = fromGuid;
myEmail.from = new activityparty[] { from };

activityparty[] apTo = new activityparty[toGuid.Count];
// creating as many activity party as the no of users or members in a team
int i = 0;
foreach (String memberID in toGuid)
{
apTo[i] = new activityparty();
apTo[i].partyid = new Lookup();
apTo[i].partyid.type = EntityName.systemuser.ToString();
apTo[i].partyid.Value = new Guid(memberID);
i++;
}

myEmail.to = apTo;
TargetSendFromTemplateEmail myTargetSendFromTemplateEmail = new TargetSendFromTemplateEmail();
myTargetSendFromTemplateEmail.Email = myEmail;
SendEmailFromTemplateRequest mySendEmailFromTmpRequest = new SendEmailFromTemplateRequest();
// Specify entity instance id for RegardingID
mySendEmailFromTmpRequest.RegardingId = recordRegardingID;
// Specify the type of entity
mySendEmailFromTmpRequest.RegardingType = enitityName.ToString();
// Specify the email instance to be sent
mySendEmailFromTmpRequest.Target = myTargetSendFromTemplateEmail;
// Specify the template to be used ( Either a global or created specfially for that entity)
mySendEmailFromTmpRequest.TemplateId = templateId;
SendEmailFromTemplateResponse mySendEmailFromTmpResponse =(SendEmailFromTemplateResponse)service.Execute(mySendEmailFromTmpRequest);

}

Revoke Access To Entity


private bool RevokeAccessToEntity(ICrmService service, Guid guidValue, Guid entityID, string EntityName)
{
bool isSuccess = false;
// Create the SecurityPrincipal object.
SecurityPrincipal principal = new SecurityPrincipal();

// PrincipalId is the GUID of the team whose access is being revoked.
principal.Type = SecurityPrincipalType.Team;

principal.PrincipalId = guidValue;

// Create the target for the request.
TargetOwnedDynamic target = new TargetOwnedDynamic();
// EntityId is the GUID of the Opportunity to which
// access is being revoked.
target.EntityId = entityID;
target.EntityName = EntityName;

// Create the request object.
RevokeAccessRequest revoke = new RevokeAccessRequest();
// Set the properties of the request object.
revoke.Revokee = principal;
revoke.Target = target;
// Execute the request.

try
{
RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
throw ex;
}
return isSuccess;

}

AutoNumber Plug-In for Custom Entity In CRM 4.0


using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.Crm.Sdk;

using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Sdk.Query;

using System.Web.Services.Protocols;

namespace CRM.Customization.AutoNumber

{

public class AutoNumberPlugIns:IPlugin

{

DynamicEntity entity = null;

int startNumber;

string prefix = string.Empty;

string seperator = string.Empty;

int nextMaxNumber;

string uniqueId = string.Empty;

#region IPlugin Members

public void Execute(IPluginExecutionContext context)

{

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

context.InputParameters.Properties[“Target”] is DynamicEntity)

{

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

ICrmService service = context.CreateCrmService(true);

if (entity.Name ==“new_testentity”)

{

// Find maximum number

int maxNumber = FindMaxNumber(service);

nextMaxNumber=maxNumber + 1;

if (nextMaxNumber > 0)

{

bool isRetrivePrefixSuccess = RetrievePrefixSufixAndStartNumber(service);

if (isRetrivePrefixSuccess)

{

if (nextMaxNumber >= startNumber)

{

string buildAutoNumber = prefix + seperator + nextMaxNumber.ToString();

uniqueId = buildAutoNumber;

StringProperty uId = new StringProperty(“new_uniqueid”, uniqueId);

entity.Properties.Add(uId);

CrmNumber nextNumber = new CrmNumber();

nextNumber.Value = nextMaxNumber;

CrmNumberProperty uniqueNo = new CrmNumberProperty(“new_uniqueno”, nextNumber);

entity.Properties.Add(uniqueNo);

}

}

}

}

}

}

private int FindMaxNumber(ICrmService service)

{

int maxNo=0;

QueryExpression query = new QueryExpression();

query.EntityName = “new_testentity”;

ColumnSet cols = new ColumnSet();

cols.AddColumn(“new_uniqueno”);

query.ColumnSet = cols;

query.AddOrder(“new_uniqueno”, OrderType.Descending);

PagingInfo pageInfo = new PagingInfo();

pageInfo.Count = 1;

pageInfo.PageNumber = 1;

query.PageInfo = pageInfo;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);

DynamicEntity testEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

for (int i = 0; i < testEntity.Properties.Count; i++)

{

if (testEntity.Properties.Contains(“new_uniqueno”))

{

CrmNumber uniqueNumber = (CrmNumber)testEntity.Properties[“new_uniqueno”];

maxNo = uniqueNumber.Value;

}

}

return maxNo;

}

private bool RetrievePrefixSufixAndStartNumber(ICrmService service)

{

try

{

QueryByAttribute query = new QueryByAttribute();

query.EntityName = “new_autonumber”;

ColumnSet cols = new ColumnSet();

cols.AddColumn(“new_startnumber”);

cols.AddColumn(“new_prefix”);

cols.AddColumn(“new_currentnumber”);

cols.AddColumn(“new_separator”);

query.ColumnSet = cols;

query.Attributes = new string[] { “new_entityname” };

query.Values = new object[] { “new_testentity” };

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);

DynamicEntity dynamicsEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

if (dynamicsEntity.Properties.Count > 0)

{

// DynamicEntity autoNumberEntity = (DynamicEntity)dynamicsEntity.BusinessEntities[0];

// Extract the fullname from the dynamic entity string fullname;

for (int i = 0; i < dynamicsEntity.Properties.Count; i++)

{

if (dynamicsEntity.Properties.Contains(“new_startnumber”))

{

CrmNumber startNo = (CrmNumber)dynamicsEntity.Properties[“new_startnumber”];

startNumber = startNo.Value;

}

if (dynamicsEntity.Properties.Contains(“new_prefix”))

{

String prefixId = (String)dynamicsEntity.Properties[“new_prefix”];

prefix = prefixId.ToString();

}

if (dynamicsEntity.Properties.Contains(“new_separator”))

{

String seperaterId = (String)dynamicsEntity.Properties[“new_separator”];

seperator = seperaterId.ToString();

}

}

}

return true;

}

catch (SoapException ex)

{

throw ex;

}

}

}

#endregion

}

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>

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

connection.Open();

 

/// Write Logic here

 

connection.Close();

 

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

connection.Open();

 

/// Write Logic here

 

connection.Close();

 

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

http://msdn.microsoft.com/en-us/library/ms186297.aspx

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…….

 

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 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”, 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”, 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;

}

%d bloggers like this: