Remoting and Webservices

(B) Which class does the remote object has to inherit ?

All remote objects should inherit from System.MarshalbyRefObject.

(I) What are two different types of remote object creation mode in .NET ?

There are two different ways in which object can be created using Remoting :-

SAO (Server Activated Objects) also called as Well-Known call mode.

CAO (Client Activated Objects)

SAO has two modes “Single Call” and “Singleton”. With Single Call object the object is

created with every method call thus making the object stateless. With Singleton the object

is created only once and the object is shared with all clients.

CAO are stateful as compared to SAO. In CAO the creation request is sent from client

side. Client holds a proxy to the server object created on server.

(A) Describe in detail Basic of SAO architecture of Remoting?

For these types of questions interviewer expects small and sweet answers. He is basically

looking at what you know about the specific subject. For these type of question this book

will provide detail code which is not necessary to be said during interview. Only the basic

steps and overall brief are enough to convince that you have knowledge about the subject.

Even though this question has detail code and answer say only what is needed in interview.

152

Remoting has at least three sections :-

Common Interface which will be shared between them.

Server.

Client.

Figure :- 4.3 Solution Explorer of Remoting Project

In CD “RemotingSample(SAO)” project is provided which gives a insight of remoting.

Above is the figure which shows the three important project sections needed to implement

remoting.

First important section is the common interface between Server and

Client.”InterFaceRemoting” project has the interface code. For sample project interface

is very simple with only two methods :- SetValue and GetValue.

Public Interface InterFaceRemoting

Sub SetValue(ByVal value As String)

Function GetValue() As String

End Interface

Second important section is the server.In this sample server is using HTTP channel and

the server object is singleton.

Imports System

Imports System.Runtime.Remoting

Imports System.Runtime.Remoting.Channels.Http

Imports System.Runtime.Remoting.Channels

Imports InterFaceRemoting

Public Class RemotingServer

Inherits MarshalByRefObject

153

Implements InterFaceRemoting.InterFaceRemoting

Private strData As String

Public Function GetValue() As String Implements

InterFaceRemoting.InterFaceRemoting.GetValue

Return strData

End Function

Sub New()

strData = “testing..”

End Sub

Public Sub SetValue(ByVal value As String) Implements

InterFaceRemoting.InterFaceRemoting.SetValue

strData = value

End Sub

End Class

Module ModuleRemotingStartUp

Sub Main()

Dim objHttpChannel As HttpChannel

Console.WriteLine(“Server Started….”)

objHttpChannel = New HttpChannel(1234)

ChannelServices.RegisterChannel(objHttpChannel)

RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),

“RemoteObject”, WellKnownObjectMode.Singleton)

Console.WriteLine(“Server registered and listening waiting

for clients…”)

Console.ReadLine()

End Sub

End Module

Following is detail explanation :-

Channel object is created and registered.

Following is the code.

Dim objHttpChannel As HttpChannel

Console.WriteLine(“Server Started….”)

objHttpChannel = New HttpChannel(1234)

ChannelServices.RegisterChannel(objHttpChannel)

Server then hosts the object so that client can connect to it. This is the time

when we specify what mode the server object will be created i.e. Singleton or

SingleCall. This is done by the following below given code. Note in sample we

154

are hosting the server object in singleton mode that means that the same object

will be shared between all clients. Also note the server object is implementing

“InterFaceRemoting” and inheriting from “MarshalByRefObject”.

RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),

“RemoteObject”, WellKnownObjectMode.Singleton)

Now comes the final section that is third section the client which will connect to this

hosted remoting object.

Following is a detail explanation of client code :-

First we create the channel i.e. HTTP. Note whatever channel the server is

using same will be used by the client.

ChannelServices.RegisterChannel(objHttpChannel)

As said before the common interface i.e.“InterFaceRemoting” will be used

to communicate with client.

After that we can get the server object reference using following code

objRemoting = CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),

“http://localhost:1234/RemoteObject”), InterFaceRemoting.InterFaceRemoting)

Then the client can make method call as if the object is local. But actually the

object is a proxy.

Console.WriteLine(“Value on server :- “ & objRemoting.GetValue.ToString())

Imports System

Imports System.Runtime.Remoting

Imports System.Runtime.Remoting.Channels.Http

Imports System.Runtime.Remoting.Channels

Imports InterFaceRemoting

Module ModuleStartClient

Sub Main()

Dim objHttpChannel As New HttpChannel

Dim objRemoting As InterFaceRemoting.InterFaceRemoting

ChannelServices.RegisterChannel(objHttpChannel)

objRemoting =

CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),

“http://localhost:1234/RemoteObject”),

155

InterFaceRemoting.InterFaceRemoting)

Console.WriteLine(“Referenced the main object…. Now

displaying Data”)

Console.WriteLine(“Value on server :- “ &

objRemoting.GetValue.ToString())

Console.WriteLine(“Press enter to Terminate”)

Console.ReadLine()

End Sub

End Module

You an run the program and see the output. For running the program run the server

program which is in server directory. Run “Server.exe” from BIN directory. If the EXE

runs properly following will be the screen as shown below.

Figure :- 4.4 Running Server Program of Remoting

Now run “Client.exe” from client folder in BIN directory.Following will be the output

seen.This means that the client connected to the server program and displayed the data in

the server object. In the server object we have initialized value “testing……”. In constructor

of class “RemotingServer” same value is displayed at the client side as shown in figure

below.

156

Figure :- 4.5 Client Program output of Remoting

(A) What are the situations you will use singleton architecture in

remoting ?

If all remoting clients have to share the same data singleton architecture will be used.

(A) What is fundamental of published or precreated objects in Remoting

?

In scenarios of singleton or single call the objects are created dynamically. But in situations

where you want to precreate object and publish it you will use published object scenarios.

Dim obj as new objRemote

obj.Initvalue = 100

RemotingServices.Marshal(obj,”RemoteObject”)

As shown in above sample following changes will be needed on server side.

RemotingConfiguration.RegisterWellKnownServiceType is replaced by

RemotingServices.Marshal(obj,”RemoteObject”) where “obj” is the precreated objected

on the server whose value is initialized to 100.

(A) What are the ways in which client can create object on server in CAO

model ?

There are two ways by which you can create Client objects on remoting server :-

157

Activator.CreateInstance().

By Keyword “New”.

(A) Are CAO stateful in nature ?

Yes. In CAO remoting model client creates a instance on server and instance variable set

by client on server can be retrieved again with correct value.

(A) In CAO model when we want client objects to be created by “NEW”

keyword is there any precautions to be taken ?

Remoting Clients and Remoting Server can communicate because they share a common

contract by implementing Shared Interface or Base Class (As seen in previous examples).

But according to OOP’s concept we can not create a object of interface or Base Classes

(Abstract Class). Shipping the server object to client is not a good design practice. In

CAO model we can use SOAPSUDS utility to generate Metadata DLL from server which

can be shipped to client, clients can then use this DLL for creating object on server. Run

the SOAPSUDS utility from visual studio command prompt for syntax see below :-

soapsuds -ia:RemotingServer -nowp -oa:ClientMetaData.dll

Where RemotingServer is your server class name.

ClientMetaData.dll is the DLL name by which you will want to create the metadll.

Server code will change as follows :-

ChannelServices.RegisterChannel(objHttpChannel)

RemotingConfiguration.ApplicationName = “RemoteObject”

RemotingConfiguration.RegisterActivatedServiceType(GetType(InterFaceRemoting.InterFaceRemoting))

Note :- We have to provide applicationname and register the object as ActivatedServiceType.

On client side we have to reference the generated ClientMetaData.dll from SOAPSUDS

utility. Below are changes which are needed to be incorporated at the Remoting Client :-

RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObject),“http://

localhost:1234/MyServer”)

Dim objRemoteObject as new RemoteObject().

158

RemoteObject is class which is obtained from ClientMetaData.dll which we created using

SOAPSUDS utility. Now you can reference the object as normal object.

(I) Is it a good design practice to distribute the implementation to

Remoting Client ?

It’s never advisable to distribute complete implementation at client, due to following

reasons:-

Any one can use ILDASM and decrypt your logic.

It’s a bad architecture move to have full implementation as client side as any

changes in implementation on server side you have to redistribute it again.

So the best way is to have a interface or SOAPSUDS generated meta-data DLL at client

side rather than having full implementation.

(A) What are LeaseTime, SponsorshipTime, RenewonCallTime and

LeaseManagerPollTime?

This is a very important question from practical implementation point of view. Companies

who have specific requirement for Remoting projects will expect this question to be answered.

In normal .NET environment objects lifetime is managed by garbage collector. But in

remoting environment remote clients can access objects which are out of control of

garbage collector. Garbage collector boundary is limited to a single PC on which framework

is running; any remote client across physical PC is out of control of GC (Garbage

Collector).

This constraint of garbage collector leads to a new way of handling lifetime for remoting

objects, by using concept called as “LeaseTime”. Every server side object is assigned by

default a “LeaseTime” of five minutes. This leasetime is decreased at certain intervals.

Again for every method call a default of two minutes is assigned. When i say method call

means every call made from client. This is called as “RenewalOnCallTime”.

Let’s put the whole thing in equation to make the concept more clear.

Total Remoting object life time = LeaseTime + (Number of method calls) X

(RenewalTime).

If we take NumberOfMethodCalls as one.

159

Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in

minutes)

When total object lifetime is reduced to zero, it queries the sponsor that should the object

be destroyed. Sponsor is an object which decides should object Lifetime be renewed. So

it queries any registered sponsors with the object, if does not find any then the object is

marked for garbage collection. After this garbage collection has whole control on the

object lifetime. If we do not foresee how long a object will be needed specify the

“SponsorShipTimeOut” value. SponsorShipTimeOut is time unit a call to a sponsor is

timed out.

“LeaseManagerPollTime” defines the time the sponsor has to return a lease time extension.

(A) Which config file has all the supported channels/protocol ?

Machine.config file has all the supported channels and formatter supported by .NET

remoting.Machine.config file can be found at

“C:\WINDOWS\Microsoft.NET\Framework\vXXXXX\CONFIG” path. Find

<system.runtime.remoting> element in the Machine.config file which has the channels

and the formatters. Below is a figure shown which can give a clear idea of how the file

looks like.

Note :- Interviewer will not ask you to name all channels and formatters in machine.config

but will definitely like to know in which file are all the formatter and channels specified, one

sweet answer “Machine.config” can fetch you handsome job.

160

Figure :- 4.6 Channels and Formatter in machine.config file

(A) How can you specify remoting parameters using Config files ?

Both remoting server and remoting client parameters can be provided through config

files. Below is a sample of server config file which provides all remoting parameter values

which we where providing through code.

<configuration>

<system.runtime.remoting>

<application name=”Server”>

<service>

<wellknown

161

mode=”SingleCall”

type=”Server.ClsServer, Server”

objectUri=”RemoteObject” />

</service>

<channels>

<channel ref=”tcp server” port=”9000″ />

</channels>

</application>

</system.runtime.remoting>

</configuration>

Later this config file can be loaded using the following code.

RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase

& “Server.config”)

Same way we also have client.config file for loading the client remoting parameters.

<configuration>

<system.runtime.remoting>

<application name=”Client”>

<client url=”tcp://localhost:9000/RemoteObject”>

<wellknown

type=”CommonInterface.Icommon, Icommon”

url = “tcp://localhost:9000/Server/RemoteObject”/>

</client>

<channels>

<channel ref=”tcp client” />

</channels>

</application>

</system.runtime.remoting>

</configuration>

client remoting can then load the configuration file by using :-

Dim IobjCommon As CommonInterFace.Icommon

Dim StrData As String

Dim objServiceEntries As WellKnownClientTypeEntry()

RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase

& “Client.config”)

objServiceEntries =

RemotingConfiguration.GetRegisteredWellKnownClientTypes()

IobjCommon = Activator.GetObject(GetType(Icommon),

objServiceEntries(0).ObjectUrl.ToString())

StrData = IobjCommon.GetValue()

162

Console.WriteLine(“ Serve side Data is “ & StrData)

Console.ReadLine()

Note :- Complete source is provided in CD in folder “RemotingObjectLifeTime”.If you run

Server and Client following output can be seen. All source is compiled using VS2005

BETA1

Figure : – 4.7 Output of Server and Client for RemotingObjectLifeTime project

(A) Can Non-Default constructors be used with Single Call SAO?

Twist :- What are the limitation of constructors for Single call SAO ?

163

Non-Default constructors can not be used with single call objects as object is created

with every method call, there is no way to define Non-default constructors in method

calls.

It’s possible to use Non-Default constructor with Client activated objects as both methods

:-

“NEW” keyword and “Activator.CreateInstance” provide a way to specify Non-Default

constructors.

(I) How can we call methods in remoting Asynchronously ?

All previous examples are a synchronous method calls that means client has to wait until

the method completes the process. By using Delegates we can make Asynchronous method

calls.

(A) What is Asynchronous One-Way Calls ?

One-way calls are a different from asynchronous calls from execution angle that the .NET

Framework does not guarantee their execution. In addition, the methods used in this kind

of call cannot have return values or out parameters. One-way calls are defined by using

[OneWay()] attribute in class.

(B) What is marshalling and what are different kinds of marshalling ?

Marshaling is used when an object is converted so that it can be sent across the network

or across application domains. Unmarshaling creates an object from the marshaled data.

There are two ways to do marshalling :-

Marshal-by-value (MBV) :- In this the object is serialized into the channel, and

a copy of the object is created on the other side of the network. The object to

marshal is stored into a stream, and the stream is used to build a copy of the

object on the other side with the unmarshalling sequence.

Marshaling-by-reference (MBR):- Here it creates a proxy on the client that is

used to communicate with the remote object. The marshaling sequence of a

remote object creates an ObjRef instance that itself can be serialized across

the network.

Objects that are derived from “MarshalByRefObject” are always marshaled by reference.

All our previous samples have classes inherited from “MarshalByRefObject”

164

To marshal a remote object the static method RemotingServices.Marshal() is

used.RemotingServices.Marshal() has following overloaded versions:-

public static ObjRef Marshal(MarshalByRefObject obj)

public static ObjRef Marshal(MarshalByRefObject obj, string objUri)

public static ObjRef Marshal(MarshalByRefObject obj, string objUri,Type

requestedType)

The first argument obj specifies the object to marshal. The objUri is the path that is

stored within the marshaled object reference; it can be used to access the remote object.

The requestedType can be used to pass a different type of the object to the object reference.

This is useful if the client using the remote object shouldn’t use the object class but an

interface that the remote object class implements instead. In this scenario the interface is

the requestedType that should be used for marshaling.

(A) What is ObjRef object in remoting ?

All Marshal() methods return ObjRef object.The ObjRef is serializable because it

implements the interface ISerializable, and can be marshaled by value. The ObjRef knows

about :-

location of the remote object

host name

port number

object name.

(B) What is a Web Service ?

Web Services are business logic components which provide functionality via the Internet

using standard protocols such as HTTP.

Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business

functionality.SOAP defines a standardized format in XML which can be exchanged

between two entities over standard protocols such as HTTP. SOAP is platform independent

so the consumer of a Web Service is therefore completely shielded from any

implementation details about the platform exposing the Web Service. For the consumer it

is simply a black box of send and receive XML over HTTP. So any web service hosted on

windows can also be consumed by UNIX and LINUX platform.

165

(B) What is UDDI ?

Full form of UDDI is Universal Description, Discovery and Integration. It is a directory

that can be used to publish and discover public Web Services. If you want to see more

details you can visit the http://www.UDDI.org .

(B) What is DISCO ?

DISCO is the abbreviated form of Discovery. It is basically used to club or group common

services together on a server and provides links to the schema documents of the services

it describes may require.

(B) What is WSDL?

Web Service Description Language (WSDL)is a W3C specification which defines XML

grammar for describing Web Services.XML grammar describes details such as:-

Where we can find the Web Service (its URI)?

What are the methods and properties that service supports?

Data type support.

Supported protocols

In short its a bible of what the webservice can do.Clients can consume this WSDL and

build proxy objects that clients use to communicate with the Web Services. Full WSDL

specification is available at http://www.w3.org/TR/wsdl.

(A) What the different phase/steps of acquiring a proxy object in

Webservice ?

Following are the different steps needed to get a proxy object of a webservice at

the client side :-

Client communicates to UDI node for WebService either through browser or

UDDI’s public web service.

UDII responds with a list of webservice.

166

Every service listed by webservice has a URI pointing to DISCO or WSDL

document.

After parsing the DISCO document, we follow the URI for the WSDL document

related to the webservice which we need.

Client then parses the WSDL document and builds a proxy object which can

communicate with Webservice.

(B) What is file extension of Webservices ?

.ASMX is extension for Webservices.

Note :- After this we are going to deal with a sample of webservice. In VS2005 webproject

is created from the menu itself as compared to 2003 where it was present in the explorer.

167

Figure :- 4.8 Create Web project menu in VS2005

(B)Which attribute is used in order that the method can be used as

WebService ?

WebMethod attribute has to be specified in order that the method and property can be

treated as WebService.

(A) What are the steps to create a webservice and consume it ?

Note :- For this question this book will make a attempt by creating a simple webservice and

explaining steps to acheive it. A simple webservice will be created which takes two number

and gives addition result of the two number. In CD sample webservice project with folder

name “MathsWebService” is provided and same will be explained below. Definitely the

168

interviewer will not expect such a detail answer but this book will explain you in detail so

that you are on right track during interview.

This webservice will add two numbers and give to the calling client.All the below steps

are according to VS2005 beta editor :-

First create a website by clicking on File — New WebSite.

From “Visual Studio Installed Templates” click on “Asp.NET Web Service”.

See figure below. Name the figure as “Maths Web Service”.

169

Figure :- 4.9 Create WebService Project

By default the .NET editor has made a default webservice method called as

“HelloWord” which returns a string datatype. Let’s rename “Service.vb” to

“Maths.vb” and “Service.asmx” to “Maths.asmx”. Let’s replace the

“HelloWorld” with following code below :-

<WebMethod()> _

Public Function AddTwoNumbers(ByVal Number1 As Integer, ByVal

Number2 As Integer) As Integer

Return Number1 + Number2

170

End Function

Figure :- 4.10 Rename all your default “Service” to “Maths”

After the webservice is done click on add Webreference. Normally for

components we do a “Add Reference” and for Webservices we do “Add Web

Reference”.

171

Figure :- 4.11 Click on Add Web Reference

You will be shown with a list of webservices which are known to the

solutions. As we are looking for our “Maths” webservice which exist in the

172

same solution, we click “Webservices in this solution”.

Figure :- 4.12 List of webservices for browsing

Your editor has located the “Maths” webservice.Select the webservice.

173

Figure :- 4.13 Solution showing the availability of Maths Webservice.

174

After you have clicked on “Maths” webservice you will see a search progress

bar as shown in figure below. This process will start the webservice, reference it

and create a proxy for the client, so that using it client can absorb the

webservice.

Figure :- 4.14 Starting the webservice and creating the proxy for your solution.

175

Finally you are able to see your webservice which is ready for use. Click on

Add Reference and you will see a “Localhost” reference in your .NET solution.

Figure :- 4.15 Starting the webservice and creating the proxy for your solution.

We need to make a client who will absorb this “Maths Webservice”. Add

“WebserviceClient.aspx” and create a UI as shown below. In the button click

put in the following code. “LocalHost.ClsMaths” is the proxy object by which

you can make calls to the webservice.

Sub cmdCalculate_Click(ByVal sender As Object, ByVal e As

176

System.EventArgs)

Dim pobjMaths As New localhost.ClsMaths

lblResultDisplay.Text =

Convert.ToString(pobjMaths.AddTwoNumbers(Convert.ToInt16(txtNumber1.Text),

Convert.ToInt16(txtNumber2.Text)))

End Sub

Figure :- 4.16 Complete Webservice in action.

Note :- The whole point of creating this “Maths Webservice” step by step was to have a

understanding of practical angle of how webservices are created. It’s very rare that you will

be asked to explain every step of how to write a webservice. But in case your interviewer is

too bend down to also know what are the actual steps in creating a Webservice.

(A) Do webservice have state ?

Twist :- How can we maintain State in Webservices ?

177

Webservices as such do not have any mechanism by which they can maintain state.

Webservices can access ASP.NET intrinsic objects like Session, application and so on if

they inherit from “WebService” base class.

<%@ Webservice class=”TestWebServiceClass” %>

Imports System.Web.Services

Public class TestWebServiceClass

Inherits WebService

<WebMethod> Public Sub SetSession(value As String)

session(“Val”) = Value

End Sub

end class

Above is a sample code which sets as session object called as “val”. TestWebserviceClass

is inheriting from WebService to access the session and application objects.

178

(B) What is an application object ?

Application object ca be n used in situation where we want data to be shared across users

globally.

(I)What’s the difference between Cache object and application object ?

The main difference between the Cache and Application objects is that the Cache object

provides cache-specific features, such as dependencies and expiration policies.

(I)How can get access to cache object ?

The Cache object is defined in the System.Web.Caching namespace. You can get a reference

to the Cache object by using the Cache property of the HttpContext class in the

System.Web namespace or by using the Cache property of the Page object.

(A)What are dependencies in cache and types of dependencies ?

When you add an item to the cache, you can define dependency relationships that can

force that item to be removed from the cache under specific activities of dependenci

es.Example if the cache object is dependent on file and when the file data changes you

want the cache object to be update. Following are the supported dependency :-

File dependency :- Allows you to invalidate a specific cache item when a disk

based file or files change.

Time-based expiration :- Allows you to invalidate a specific cache item

depending on predefined time.

Key dependency :-Allows you to invalidate a specific cache item depending

when another cached item changes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: