You are on page 1of 53

What is WCF?

The Windows Presentation Foundation (WPF) is a next generation graphics platform that is part of .NET 3.0 and .NET 3.5.
It allows you to build advanced user interfaces that incorporate documents, media, 2D and 3D graphics, animations, and web-like characteristics.
In just 24 sessions of one hour or less, you will be able to begin effectively using WPF to solve real-world problems, developing rich user interfaces
in less time than you thought possible. Using a straightforward, step-by-step approach, each lesson builds on a real-world foundation forged in both
technology and business matters, allowing you to learn the essentials of WPF from the ground up. *Step-by-step instructions carefully walk you
through the most common questions, issues, and tasks. *The Q&A sections, quizzes, and exercises help you build and test your knowledge.
*By the Way notes present interesting pieces of information. *Did You Know? Tips offer advice or teach an easier way to do something.
*Watch Out! Cautions advise you about potential problems and help you steer clear of disaster. Learn how to... *Use XAML to build user interfaces
*Leverage data binding to minimize tedious code *Create visually engaging applications *Architect and design WPF applications using proven
patterns such as MVP *Incorporate audio and video into your applications *Customize controls with styles, templates, and animation *Apply
best practices for developing software with WPF *Deploy WPF applications to the desktop and Web *Take advantage of WPF¡¯s advanced printing
capabilities *Grow as a developer by improving your overall software design skills.

Difference between WCF and Web services?


Web Services

1.It Can be accessed only over HTTP


2.It works in stateless environment

WCF

WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting
WCF services:
IIS
WAS
Self-hosting
Managed Windows Service

What are the various ways of hosting a WCF service?


Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you cr
object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.

What is three major points in WCF?


We Should remember ABC.

Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our
service.

Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols

Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.

What is the difference WCF and Web services?


Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protoco
http, tcp etc.) and any transport type.

Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new
Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need
about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the
communication mechanism like HTTP/TCP/MSMQ etc

For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx

What are various ways of hosting WCF Services?


There are three major ways of hosting a WCF services
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you
object of Service Host class and the service closes when you call the Close of the Service Host class.

• Host in application domain or process provided by IIS Server.

• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

More details http://www.dotnetfunda.com/articles/article221.aspx#whatarethevariouswaysofhostingaWCFservice

What was the code name for WCF?


The code name of WCF was Indigo .

WCF is a unification of .NET framework communication technologies which unites the following technologies:-

NET remoting
MSMQ
Web services
COM+

What are the main components of WCF?


The main components of WCF are

1. Service class
2. Hosting environment
3. End point

For more details read http://www.dotnetfunda.com/articles/article221.aspx#WhatarethemaincomponentsofWCF

How to set the timeout property for the WCF Service client call?

The timeout property can be set for the WCF Service client call using binding tag.

<client>

<endpoint

...

binding = "wsHttpBinding"

bindingConfiguration = "LongTimeout"

...

/>

</client>

<bindings>

<wsHttpBinding>

<binding name = "LongTimeout" sendTimeout = "00:04:00"/>

</wsHttpBinding>

</bindings>

If no timeout has been specified, the default is considered as 1 minute.


How to deal with operation overloading while exposing the WCF services?

By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribu
can deal with operation overloading scenario.

[ServiceContract]

interface ICalculator

[OperationContract(Name = "AddInt")]

int Add(int arg1,int arg2);

[OperationContract(Name = "AddDouble")]

double Add(double arg1,double arg2);

Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case clien
will have two methods with different name AddInt and AddDouble.

How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.

<system.serviceModel>

<services>

<service name = "MyService">

<endpoint

address = "net.tcp://localhost:8888/MyService"

binding = "netTcpBinding"

bindingConfiguration = "ReliableCommunication"

contract = "IMyContract"

/>

</service>

</services>

<bindings>

<netTcpBinding>

<binding name = "ReliableCommunication">

<reliableSession enabled = "true"/>


</binding>

</netTcpBinding>

</bindings>

</system.serviceModel>

Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

What is Transport and Message Reliability?

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the
the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliabili
provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops
required to deliver the message from the client to the service.
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
<system.serviceModel>

<client>

<endpoint name = "MyEndpoint"

address = "http://localhost:8000/MyService/"

binding = "wsHttpBinding"

contract = "IMyContract"

/>

</client>

</system.serviceModel>

What is Proxy and how to generate proxy for WCF Services?


The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations
service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy compl
encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication tran

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Ad
Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace
contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the me
exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out
to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the b
address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs


What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

Service contracts

Describe which operations the client can perform on the service.


There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]

interface IMyContract

[OperationContract]

string MyMethod( );

class MyService : IMyContract

public string MyMethod( )

return "Hello World";

Data contracts

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but w
easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.


DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
[DataContract]

class Contact

[DataMember]

public string FirstName;

[DataMember]

public string LastName;


}

If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts

Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts

Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases
when there is an existing message format we have to comply with.

What is the address formats of the WCF transport schemas?


Address format of WCF transport schema always follow

[transport]://[machine or domain][:optional port] format.

for example:

HTTP Address Format

http://localhost:8888
the way to read the above url is

"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.

TCP Address Format

net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:

net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format


net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name o
same machine.

MSMQ Address Format


net.msmq://localhost/private/MyService
net.msmq://localhost/MyService

How to define a service as REST based service in WCF?


WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a RESTful service
[ServiceContract]

interface IStock

[OperationContract]

[WebGet]

int GetStock(string StockId);


}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

What is endpoint in WCF?


Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that
how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding
used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure m
or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can wo
new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, in
reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the se
use WCF.

Peer network binding

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subs
the same grid and broadcast messages to it.

IPC binding

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secur
since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) binding

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliabil
transactions, and security over the Internet.

Federated WS binding

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the s
the client.

MSMQ binding

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
MSMQ integration binding

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperat
legacy MSMQ clients.

For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx

Where we can host WCF services?


Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This c
the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

What is service and client in perspective of data communication?


A service is a unit of functionality exposed to the world.

The client of a service is merely the party consuming the service.

What is WCF?

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime envir
for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

What is a service level message and transport level message?


You can log WCF message at two levels one is service level and the other is transport level. Service level:-In this the messages are logg
they enter the user code or leave the user code. Transport level: - In this the messages are logged as they are ready to be encoded / de
transport level, infrastructure messages and also reliable messaging is logged. You specify the message levels in the diagnostics node a
in the below code snippet.
<system.serviceModel>

<diagnostics>

<messageLogging
logEntireMessage="true"

logMalformedMessages="false"

logMessagesAtServiceLevel="false"

logMessagesAtTransportLevel="true"

maxMessagesToLog="3000"

maxSizeOfMessageToLog="10000"/>

</diagnostics>

</system.serviceModel>

‘Messagelogging’ also has other attributes , below is the short description about the same.

Description

Attribute

Should the entire message be logged on only the header.


logEntireMessage

Should malformed messages be logged.


logMalformedMessages

Should service-level messages be logged.


logMessagesAtServiceLevel

Should transport level messages be logged.


logMessagesAtTransportLevel

Number indicating how many messages should be logged.


maxMessageToLog
Description

Attribute

maxSizeOfMessageToLog The default value is 256Kb. Max size of the message log.

What is the concept of tracelevel in trace listeners?


In the previous question we have specified switch value as information. This value indicates what type and level of tracing information
to record. Below is the list of the same.

Description

Trace Level

Ignore all trace messages


Off

Log unexpected processing events or unhandled exceptions have occurred. The application will
Critical terminate immediately or shortly.

An unexpected processing event or exception has occurred. The application is still capable of
Error continuing its processing.

Indicates there is a possible problem but the application will continue running.
Warning

Application is running smoothly only that informative message is recorded. In this case
Information messages are just milestones.

Very similar to information but provides more details as compared.


Verbose
Description

Trace Level

In this case messages are related to communication between components and the activities.
ActivityTracing

In this case all messages are captured.


All

Trace level value is specified in ‘source’ tag in switch value. For instance the below ‘web.config’ snippet indicates the trace type as ‘Info
<system.diagnostics>

<sources>

<source name="System.ServiceModel"

switchValue="Information, ActivityTracing">

............

............

............

............

How can we enable tracing on the readymade tracing WCF objects?

We will enable tracing on ‘System.ServiceModel’ tracing object. To enable tracing we need to enable the ‘system.diagnostics’ XML node
‘web.config’ file of the WCF service. We need to also define the type of listeners for the ‘System.ServiceModel’ listener object. So we add
‘listeners’ tag with the type as ‘System.Diagnostics.XmlWriterTraceListener’. We need to also define the file and path where the file is cr
For the current scenario we have defined the file as ‘Traces.svclog’ and the folder as ‘c:\’ drive.
<system.diagnostics>

<sources>

<source name="System.ServiceModel"

switchValue="Information, ActivityTracing">

<listeners>

<add name="log"

type="System.Diagnostics.XmlWriterTraceListener"

initializeData="c:\Traces.svclog" />

</listeners>

</source>
</sources>

</system.diagnostics>

Now if you run the WCF service you can see a XML file created as shown below.

#<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">

<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">

<EventID>0</EventID>

<Type>3</Type>

<SubType Name="Transfer">0</SubType>

<Level>255</Level>

<TimeCreated SystemTime="2009-04-30T03:21:09.5625000Z" />

<Source Name="System.ServiceModel" />

<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" RelatedActivityID="{d11829b7-d2db-46d5-a4ac-49a37a5637

<Execution ProcessName="WebDev.WebServer" ProcessID="2660" ThreadID="8" />

<Channel/>

<Computer>COMPAQ-JZP37MD0</Computer>

</System>

<ApplicationData></ApplicationData>

</E2ETraceEvent>

What are the readymade trace events and they are available for which WCF objects ?
You can always use the core ‘Tracelistener’ events provided by .NET , but WCF has readymade trace listeners for the core WCF objects.

Description

Assembly Name

Logs the following :-


System.ServiceModel

• Message process
• Reading of configuration information
• Transport-level action
Description

Assembly Name

• Security requests

Generates tracing information for every message that flows through


System.ServiceModel.MessageLogging the system.

Generate trace data for authentication and authorization.


System.ServiceModel.IdentityModel

Emits information regarding activation of the service.


System.ServiceModel.Activation

Emits information when objects are serialized or deserialized. WCF


System.Runtime.Serialization always serializes and de-serializes information during request so it’s a
good event to see the content of the request.

Emits messages with respect to Common Log File System (CLFS).


System.IO.Log

Emits trace messages related to any CardSpace identity processing


CardSpace that occurs within WCF context.

Can you explain the concept of trace listener?


‘Tracelistener’ are objects that get tracing information from the trace class and they output the data to some medium. For instance you
from the figure ‘TraceListener’ how it listens to the trace object and outputs the same to UI, File or a windows event log. There are thre
different types of ‘tracelistener’ first is the ‘defaulttracelistener’ (this outputs the data to UI), second is ‘textwritertracelistener’ (this ou
a file) and the final one is ‘Eventlogtracelistener’ which outputs the same to a windows event log.
Figure - TraceListener

Below is a code snippet for ‘textwritertracelistener’ and ‘eventlogtracelistener’. Using ‘textwritertracelistener’ we have forwarded the tr
‘ErrorLog.txt’ file and in the second snippet we have used the ‘Eventlogtracelistener’ to forward the trace’s to windows event log.

Figure:- Tracelistener in action

Can you show the security differences between BasicHttpBinding VS WsHttpBinding ?


In order to understand the security differences between both these entities we will do a small project. In this project we will create two
service one service using ‘BasicHttpBinding’ and the second service using ‘WsHttpBinding’.

Step1:- So let’s first create a simple service using ‘BasicHttpBinding’. For that we just a create a simple WCF project and then modify the
‘ServiceModel’ element as shown below. You can see in the ‘endpoint’ tag we have specified ‘basicHttpBinding’ as the protocol.

<system.serviceModel>

<services>
<service name="WCFBasicHttpBinding.Service1" behaviorConfiguration="WCFBasicHttpBinding.Service1Behavior">

<!-- Service Endpoints -->

<endpoint address="" binding="basicHttpBinding" contract="WCFBasicHttpBinding.IService1">

<!--

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs. If removed, WCF will infer an appropriate identity

automatically.

-->

<identity>

<dns value="localhost"/>

</identity>

</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="WCFBasicHttpBinding.Service1Behavior">

<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment

<serviceMetadata httpGetEnabled="true"/>

<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid d
exception information -->

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Step 2 :- We also need to create one more service using ‘WsHttpBinding’. For that you do not need to anything special as such. By defau
project is created using ‘WsHttpBinding’. Below is how the Web.config file looks like. You can see how the endpoint tag is using ‘wsHttp

<system.serviceModel>

<services>

<service name="WCFWsHttpBindingHttps.Service1" behaviorConfiguration="WCFWsHttpBindingHttps.Service1Behavior">

<!-- Service Endpoints -->


<endpoint address="" binding="wsHttpBinding" contract="WCFWsHttpBindingHttps.IService1">

<!--

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs. If removed, WCF will infer an appropriate identity

automatically.

-->

<identity>

<dns value="localhost"/>

</identity>

</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="WCFWsHttpBindingHttps.Service1Behavior">

<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment

<serviceMetadata httpGetEnabled="true"/>

<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid d
exception information -->

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Step 3 :- We will not be creating any new methods in both the services. We will just use the default code created by the WCF template. S
these services will have a ‘GetData’ function which returns a string. The ‘GetData’ function is a default function created WCF project.

public class Service1 : IService1

public string GetData(int value)

{
return string.Format("You entered: {0}", value);

public CompositeType GetDataUsingDataContract(CompositeType composite)

if (composite.BoolValue)

composite.StringValue += "Suffix";

return composite;

Step 4 :- Now that out services are created we need to create a client which will consume this service. So we have created a simple web
application and we have added two references one is a service reference i.e. ‘WsHttpBinding’ and the second is a web reference i.e.
‘BasicHttpBinding’. Please note when you right click to add reference you need to use the ‘Add service reference’ to add ‘WsHttpService’
need to add web reference for ‘BasicHttpBinding’.

We will add two buttons on the default aspx page. One button will call the http service and the other will call the wshttp service. Below
the function ‘GetData’ is called in both the button clicks.
Step 5 :- So now we are ready with the complete project it is time to sniff and see how data is transported between client and the servic
the scenarios. So let’s download a simple http data recorder from http://www.ieinspector.com/httpanalyzer/download.html . We will t
both the buttons one by one and record the data transfer using httpanalyzer. You can see the posted data is in simple plain XML format
http protocol and it’s in an encrypted format for wshttp protocol.
How can we enable windows authentication on WCF using ‘BasicHttpBinding’? Part-2
Step 6:- We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if y
browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cann
executed with windows authentication.
Step 7:- So let’s consume this WCF services. So add an ASP.NET webapplication and do a add webreference. You will be popped up with
box as shown below. Click on add reference so that a proxy is generated for the WCF service.
Step 8:- Type in the following code snippet in your page load. So add the namespace reference and call the method ‘GetData’. The most
step to note is the credential supplied. ‘DefaultCredentials’ passes the current windows identity to the WCF service.

If you execute the service you should get the following display as shown below.
You can try commenting the below code in your client in other words we are not passing any credentials.

obj.Credentials = System.Net.CredentialCache.DefaultCredentials;

Now if you execute you should get the below error stating that this is a unauthorized call.

Source Code

Whatever code we have discussed in the above FAQ . You can download the Source Code from here

How can we enable windows authentication on WCF using ‘BasicHttpBinding’? Part-1


Step 1:- Create a project of WCF service application as shown in the below figure.
Circle WCF service application ?Select this

By default the WCF project creates a class file which has ‘GetData’ function. This function takes in a number values and displays a expla
sentence like ‘You entered 1 value’ , in case you have entered ‘1’.

public class Service1 : IService1

public string GetData(int value)

return string.Format("You entered: {0}", value);

Step 2:- When we create a WCF service application it also has a web.config file associated with it. So open the web.config file and ensur
authentication mode is windows.

<authentication mode="Windows" />

Step 3:- The third step is to define the bindings and the transport type. To define the bindings we need to enter ‘basicHttpBinding’ eleme
the ‘bindings’ XML tag. We also need to define the ‘clientCredentialType’ as windows.
<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="BasicHttpEndpointBinding">

<security mode="TransportCredentialOnly">

<transport clientCredentialType="Windows" />

</security>

</binding>

</basicHttpBinding>

</bindings>

<services>

.........

.........

</system.serviceModel>

Step 4:- Now the bindings defined needs to be associated with service interface i.e. ‘service1’. So we need to modify the services elemen
shown below. You can note that we have defined a end point which has the binding association.

<system.serviceModel>

........

........

........

<services>

<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">

<endpoint address="" binding="basicHttpBinding"

bindingConfiguration="BasicHttpEndpointBinding"

name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">

<identity>

<dns value="localhost" />

</identity>

</endpoint>

</service>

</services>

.........

.........
.........

.........

</system.serviceModel>

So over all your <system.serviceModel> XML part as whole with bindings and services is a shown below.

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="BasicHttpEndpointBinding">

<security mode="TransportCredentialOnly">

<transport clientCredentialType="Windows" />

</security>

</binding>

</basicHttpBinding>

</bindings>

<services>

<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">

<endpoint address="" binding="basicHttpBinding"

bindingConfiguration="BasicHttpEndpointBinding"

name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">

<identity>

<dns value="localhost" />

</identity>

</endpoint>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">

<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment

<serviceMetadata httpGetEnabled="true"/>

<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid d
exception information -->

<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Step 5 :- Go to IIS properties and click on security tab and ensure that anonymous access is disabled and only windows authentication i
enabled.

Countinue Part 2

When should we use WsHttp as compared to BasicHttp ?

If you are looking for back ward compatibility and to support lot of clients then basic http binding is the way to go or else WsHttp is the
way to start if you are seeing your clients made in .NET 3.0 and above.

So what are the scenarios, advantages and disadvantages of transport VS message security?

Transport Message
When there are no intermediate systems in between When there are intermediate systems like one
Scenarios when we this is the best methodology. more WCF service through which message is
should be using one of routed then message security is the way to go.
them

If it’s an intranet type of solution this is most


recommended methodology.

Advantages • Does not need any extra coding as protocol • Provides end to end security as it’s not
inherent security is used. dependent on protocol. Any
• Performance is better as we can use intermediate hop in network does not
hardware accelerators to enhance affect the application.
performance.
• There is lot of interoperability support and • Supports wide set of security options
communicating clients do not need to as it is not dependent on protocol. We
understand WS security as it’s built in the can also implement custom security.
protocol itself.

Disadvantages • As it’s a protocol implemented security so it • Needs application refactoring to


works only point to point. implement security.
• As every message is encrypted and
signed there are performance issues.
• As security is dependent on protocol it has
limited security support and is bounded to
the protocol security limitations. • Does not support interoperability with
old ASMX webservices/
Figure: - Route paths

For which bindings are transport, message and mixed mode supported?
Note :- The below table is taken from book Pro WCF: Practical Microsoft SOA Implementation -- Chris peiris and Denis mulder – Apress

Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It’s nothing but combinat
transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is
but message security and HTTPS is a transport mode. In a combination they form mixed mode.

Transport Mode? Message Mode? Mixed Mode?

Binding

Yes Yes Yes


BasicHttpBinding

Yes Yes Yes


WsHttpBinding
Transport Mode? Message Mode? Mixed Mode?

Binding

No Yes No
WsDualHttpBinding

Yes Yes Yes


NetTcpBinding

Yes No No
NetNamedPipeBinding

Yes Yes No
NetMsmqBinding

Yes No No
MsmqIntegrationBinding

What is transport level and message level security?


When we talk about WCF security there are two aspects, the first is the data and the second is the medium on which the data travels i.e
protocol. WCF has the ability to apply security at the transport level (i.e. protocol level) and also at message level (i.e. data).
Figure: - Transport and Message level security

Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communic
level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of
common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security
mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways
implementing message level security is by encrypting data using some standard encryption algorithm.

AJAX

How can we consume data directly in web services?

We can consume data directly using ‘Sys.Data’ controls. We know this is a very short answer for such an important
question, but the bandwidth of this book does not allow for the same. We suggest the readers to practice some
sample using the ‘Sys.Data’ control.
Note: - We have left important controls like Data controls, Login controls, Web part controls, mobile controls and
profilescriptservice control. These controls will be rarely asked during interviews, but from project aspects they are
very important.

How do we consume web service in Atlas?

There are two ways by which we can consume a web service one is using ‘Services’ tag and the other is by using
properties defined in Ajax components like ‘ServicePath’ , ‘ServiceMethod’ and ‘ServiceURL’.
We can define the web service URL in the ‘Services’ tag using ‘atlas:ServiceReference’ tag. ‘Path’ property defines the
web service URL. If we also want to generate javascript proxy we need to set the ‘GenerateProxy’ to true. We have
also set one more property i.e. ‘InlineProxy’ property needs to be true so that the proxy code is available to the client
javascript.

Figure 18.17 :- Referencing web service

If you make ‘InLineProxy’ property to true you should see the below code snippet when do a view source on the
browser.

<script type="text/javascript">

var WebService=new function()

this.appPath = "http://localhost:4430/AtlasWebSite3/";

var cm=Sys.Net.ServiceMethod.createProxyMethod;

cm(this,"HelloWorld");

cm(this,"GetWordList");

Let’s look at the second method using ‘ServiceMethod’ and ‘ServicePath’. Atlas components which display data to the
end user have certain properties which help you in consuming web service and invoke methods on those web services.
So let’s demonstrate a simple sample using the ‘AutoCompleteExtender’ component. ‘AutoCompleteExtender’ is used
to enhance a text box with auto complete functionalities. Below is a text box which is enhanced with the
‘AutoComplete’ feature.
Figure 18.18: - Textbox with AutoComplete feature

So let’s first define the web service. Below is a simple web service which exposes a word list for implementing the
auto complete feature in the text box.

Figure 18.19: - Web Service for auto complete functionality

Once we have defined the web service we need to drag and drop the ‘AutoCompleteExtender’ on the ASPX page.
Figure 18.20: - Drag and drop AutoCompleteExtender

Now if you do a view source you should see the below code in HTML. We have numbered the code to highlight the
important section.

• 1 -> This is the ‘autocompleteextender’ tag which is dragged and dropped from the tool box.
• 2 -> We need to specify the web service URL and the method of the web service. These can be defined using
‘ServiceMethod’ and ‘ServicePath’ properties.
• 3 -> We also need to define which text box control the ‘AutoCompleteExtender’ will be point to. This is
achieved by using the ‘TargetControlId’ property.

That’s it, run the program and see text box performing the auto extender functionality.
Figure 18.21: - ServiceMethod and ServicePath

The ‘ServiceURL’ property can be found in DataSource control.

How do we do exception handling in Ajax?

Exception handling in Ajax is done using the ‘ErrorTemplate’ which forms the child tag of ‘ScriptManager’. There are
three steps to achieve error handling in Ajax. Below figure ‘ErrorHandling’ in Ajax shows the three steps in a pictorial
fashion.
Figure 18.16:- Error Handling in Ajax

• Step 1 -> Right click on the script manager and click ‘Create Error Template’.
• Step 2 -> Once done click on ‘Edit Templates’.
• Step 3 -> Enter which error message you want to display when there is a error and then finally click ‘End
Template Editing’.

Just click back on the HTML view to see what we have in the HTML. You can see the ‘ErrorTemplate’ tag is the
fundamental driver for handling errors.

How can you do validations in Ajax?


We can perform all the necessary validation like required field, type checking, range checking etc using Ajax. Below is
a small snippet which shows how to use a required field validator. We have numbered the code snippet to understand
the code more proper.

• 1 -> We have defined a text box ‘TextBox1’ which will be validated for required field.
• 2 -> We have defined a simple ‘<span>’ HTML tag which will display the error message.
• 3, 4 and 5 -> We use the XML declarative Ajax script to define that ‘TextBox1’ has validators and it’s a
required field validator. To define the required field validator we need the ‘RequiredFieldValidator’ controls
inside the validators.
• 6 -> We then define where the error should be displayed using the ‘ValidationErrorLabel’. In this case we will
be displaying error in the span ‘Validator1’ which was defined previously.

Figure 18.15:- Validations in Ajax

Note: - The above sample shows a sample for 'requiredFieldValidator' , but we can also use other validators like
rangeValidator, typeValidator, rangeValidator and regexValidator. As this is a interview book we will not be getting in
to details of the other validators, please feel free to practice some sample for the same.

Can you explain the ‘UpdateProgress’ component?

Some times we have huge task at the back end for processing and we would like to show a user friendly message
until the processing finishes. That’s where the ‘UpdateProgress’ control comes in to picture.
To use ‘UpdateProgress’ control we need to use ‘UpdatePanel’ tag. ‘UpdateProgress’ forms the child tag of
‘UpdatePanel’ control. Until the server processing finishes we can display a message which can be defined in the
‘ProgressTemplate’ tag which is the child tag of ‘UpdateProgress’ tag.

Figure 18.14:- Update Progress in action

Can you explain the concept of triggers in ‘UpdatePanel’ control?

Triggers are child tags for ‘UpdatePanel’ tag. Many times we would like to update the panel when some event occurs
or a value change on a control. This can be achieved by using triggers. There are two types of triggers
‘ControlEventTrigger’ and ‘ControlValueTrigger’. So let’s first understand ‘ControlEventTrigger’. Using
‘ControlEventTrigger’ we define on which control and at which event the update panel should refresh. Below is a
simple code snippet for ‘ControlEventTrigger’. ‘ControlEventTrigger’ are defined using ‘<atlas:ControlEventTrigger>’
tag. We have numbered the code snippet below so let’s understand the same with numbers:-

• 1 -> We need to define ‘ControlEventTrigger’ using ‘<atlas:ControlEventTrigger>’ tag.


• 2 -> In this sample we will link trigger in ‘UpdatePanel1’ with the click event of ‘Button1’.
• 3 -> In the ‘<atlas:ControlEventTrigger>’ tag we need to define the control and event using ‘ControlId’ and
‘EventName’ properties respectively.
So now when the button click event happens ‘UpdatePanel1’ is refreshed.

Figure 18.12: - Code snippet for ‘ControlEventTrigger’

Using ‘ControlValueTrigger’ we can update a panel when an external control has reached some value. So again we
need to define the same in a ‘Triggers’ tag. We need to put the ‘ControlvalueTrigger’ tag with control and property
defined using the ‘ControlId’ property. So according to below code snippet when the value of ‘Textbox1’ changes we
need to update the top panel.
Figure 18.13:- ‘ControlValueTrigger’ code snippet

Can you explain Enablepartialrendering and UpdatePanel control in Ajax?

Let’s answer the above questions with a simple sample Ajax application. As we move through this application we will
be answering the above questions. If you have already installed the Ajax setup and added the reference to
‘Microsoft.Web.Atlas.dll’ you should see those controls in your tool box as shown in the above figure ‘Ajax controls’.
Let’s follow the below steps to complete this sample:

• So first drag and drop ‘ScriptManager’ control from the tool box on the ASPX page. We have already
discussed in the previous question how important a ‘ScriptManager’ control. In order to ensure that the full
page does not post back we need to make ‘EnablePartialRendering’ to true. If this is false then the full page
will refresh.
• Now drag the ‘UpdatePanel’ control from the tool box on the ASPX page. Using ‘UpdatePanel’ we can restrict
the area of post back. In normal ASPX pages the whole page posts back i.e. there is a full refresh. But by
using ‘UpdatePanel’ we define which area has to be refreshed. ‘UpdatePanel’ forms a container for controls
and thus defining the area of post back.
• Now we drag two controls a button and textbox and put a long loop code as shown in figure ‘Long loop code’.

Below figure ‘ScriptManager and UpdatePanel' shows how the ‘ScriptManager’, ‘UpdatePanel’ and
‘EnablePartialRendering’ will look like.
Figure 18.9 : - ScriptManager and UpdatePanel

Figure 18.10: - Long loop code

Just to understand the inside basics you can switch in to the HTML of the ASPX you should see the below code snippet
as shown in figure ‘ScriptManager and UpdatePanel code view’.
Note: - ‘ScriptManager’ should come as a first control on any Ajax ASPX page.

So:

• 1 -> Defines the ‘ScriptManager’ control,


• 2 -> Defines the ‘UpdatePanel’ control,
• 3 -> all the controls should come under ‘ContentTemplate’ tag and
• 4 -> defines the controls which will be wrapped under the ‘UpdatePanel’ tag. Figure ‘Long loop code’ is called
on button1 click to do some heavy task so that we can judge the advantage of using Ajax.

Figure 18.11: - Script Manager and Update Panel code view

Once done you can check the project with ‘EnableRendering’ true and with false value to see the effect of how Ajax
actually works.

Can you explain Scriptmanager control in Ajax?

Scriptmanager control is the central heart of Ajax. They manage all the Ajax related objects on the page. Some of the
core objectives of scriptmanager control are as follows:-

• Helps load core Ajax related script and library.


• Provides access to web services.
• ASP.NET authentication, role and profile services are loaded by scriptmanager control.
• Provided registration of server controls and behaviors.
• Enable full or partial rendering of a web page.
• Provide localization features.

In short , any Ajax enable page should have this control.

How do we reference HTML controls using Atlas?

<input id="Button1" type="button" value="button" />

You can reference the above HTML defined button using the below code snippet of JavaScript. We have also attached
the on click method with the button. This method will be called when we click the button.

var btnVisibility = new Sys.UI.Button($('Button1'));

btnVisibility.intialize();

btnVisibility.click.add(onClick);

You can refer other HTML elements like Label, Textbox m Checkbox, Hyperlinks etc using the Sys.UI.

Note: - We have added some extra questions in this edition for Ajax as promised. In CD we have provided
‘AtlasSetup’. This you need to install to get the below Ajax project template in VS.NET 2005.

Figure 18.7 :- Ajax template


One more thing to ensure before we start Ajax is to add the Ajax controls on the tool box. So do the following right
click on the tool box ? click choose items ? click ‘Browse’ button ? add ‘C:\Program Files\Microsoft
ASP.NET\Atlas\v2.0.50727\Atlas\Microsoft.Web.Atlas.dll’. Once done you should see some new components as shown
in figure ‘Ajax controls’. Now we are ready to see how Ajax works.

Figure 18.8:-Ajax control

How do we do inheritance-using Atlas? OR How do we define interfaces using Atlas?

Below is a numbered code snippet, which will answer both the upper questions. Let us understand in detail the
numbered sections.

• 1 and 2 -- This defines the interface definition. Function.abstractMethod () defines a method as abstract.
• 3 - We need to register the interface, which is done by using register Interface method.
• 4, 5 and 6 - Inheritance and Interface is defined when we register the class. Register Class has three inputs.
4th section defines the main class, which needs to be registered. 5th section defines the parent class from
which it will inherit. 6th section defines the interface. So clsMyCustomCustomer is the class which derives
from clsCustomer and implements I Customer interface.
Figure 18.6:- Inheritance and Interfaces in action

How can we create a class in JavaScript using Atlas?

JavaScript is object based language and this a new feature which is provided by Atlas. Using Atlas you can now define
classes, do inheritance, create interfaces etc in JavaScript. You can now implement all the object-oriented concepts in
JavaScript. So let us understand the same with an example.
Once you install the Atlas setup you will get the following JS files and a web.config file as shown in the below figure.
In order to use Atlas you need to add the JS files in your project. You can see from the figure below we have added
the JavaScript files and the web.config file to the project that was installed with Atlas setup. We also need to add
Microsoft.Web.Atlas.dll to the project.Components.js has the class definition, which we will discuss in the coming
sections.
Figure 18.4:- Ajax folder structure

Below figure has two important code snippets the top one is taken from components’ it defines the class definition and
the second code snippet is of ASPX page which consumes the JavaScript class. So let us understand all the numbered
points one by one.

1. In this section we register namespace-using register Namespace function. We have named our namespace as
Namespace Customer.
2. Here we have defined our class clsCustomer.
3. We have defined two properties Customer Code and Customer Name. Both the properties have get and set
function. We have also defined a read-only function getCodeAndName, which returns the concatenation of
customer code and customer name.
4. Finally we register the class with the namespace.
5. In this section we have consumed the class.getCOdeAndName will display the concatenated value of
customer code and customer name.

Note: - You can find the above code in AtlasClass folder. Feel free to experiment with the same.
Figure 18.5:- Code snippet for consuming the class

How do we pass parameters to the server?

Below are the two ways of passing data to server. The first one shows by using GET and the second by POST.

xmlHttpObj.open("GET","http://" + location.host +
"/XmlHttpExample1/WebForm1.aspx?value=123", true);

xmlHttpObj.open("POST","http://" + location.host +

"/XmlHttpExample1/WebForm1.aspx?value=123", true);

Navigate to Page: 1 | 2 |

WhatarethevariousstatesinXMLHttpRequestandhowdowecheckthesame? OR
Howcanwegetresponsetext? OR
HowcanwesendrequesttotheserverusingtheXMLHttpRequestcomponent?

Note :- All the above answers are discussed in detail in the below section.

• Abort ():- This method cancels a user request.


• getAllResponseHeaders ():- Returns a collection of HTTP headers as string. If you want a specific
header value, you can use getResponseHeader (“header name”)
• Open (“method”, “URL”, “async”, “uname”, “pswd”):- This method takes a URL and other values
needed for a request. You can also specify how the request is sent by GET, POST, or PUT. One of
the important values is how this request will be sent asynchronously or synchronously. True
means that processing is carried after the send () method, without waiting for a response. False
means that processing is waits for a response before continuing.
• Send (content):- Sends a request to the server resource.
• SetRequestHeader (“label”,” value”):- Sets label value pair for a HTTP header.
• Onreadystatechange: - This is a event handler, which fires at every state change.
• Ready State: - Returns the current state of the object.

o 0 = uninitialized
o 1 = loading
o 2 = loaded
o 3 = interactive
o 4 = complete

If you want to check the state use if (xmlHttpObj.readyState ==4).

• Response Text: - Returns the response in plain string.


• Response: - Returns the response as XML. Therefore, this gives us DOM object model, which can
then be traversed.
• Status: - Returns the status as a numeric For instance 404 for "Not Found" or 200 for "OK", 500
for "Server Error" etc.
• Status Text: - Returns the status as a string. For instance, "not found" or "OK".
How do we do asynchronous processing using Ajax?

xmlHttpObj.onreadystatechange = function1();

Above is the code snippet, which will help us to do asynchronous processing. So function1 () will be called
when the XMLHTTP request object goes to on ready state change.

How do we use XMLHttpRequest object in JavaScript?

Below is a code snippet, which shows how to use XMLHttpRequest object. In this code snippet, we are
sending a GET request on the local IIS. Below is the explanation of the code snippet according to the
numbers specified in the code snippet?

• 1,2,3,4 -> This is like checking which is this browser and create the objects accordingly.
XMLHttpRequest objects have different ways of technical implementation according to different
browsers. In Internet explorer it is an activex object but in other browsers its XMLHttpRequest.
So if windows.XMLHttpRequest does not return null then we can create XMLHttpRequest object. If
it returns null then we can try creating the activex object Microsoft.XMLHttp object. In case it
fails probably then probably we have an older version of XML that is MSXML2. So in the error
handling we will try to create the MSXML2 object.
• 5 -> In this snippet, we OPEN the connection to the local host server and specify what type of
request we are using. In this case, we are using the GET method.
• 6 -> Finally, we make a request to the server.
• 7 -> Here we get the request sent by the server back to the client browser. This is a blocking call
as we need to wait to get the request back from the server. This call is synchronous that means
we need to wait for the response from the server.
Figure 18.3:- Basic XMLHTTP code

What is JSON?

JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and
object literals. JSON allows communicating with server in a standard way. JSON is used as communication
notation instead of XML.

var oBike =

"color" : "Green",

"Speed”: 200,

};

alert(oBike.color); //outputs "Green"


alert(oBike.Speed); //outputs 200

The above code creates an javascript object bike with two properties Color and Speed.

What is the fundamental behind Ajax?

XmlHttpRequest is the fundamental behind Ajax. This allows the browser to communicate to a back end
server asynchronously.XmlHttpRequest object allows the browser to communicate with server with out
posting the whole page and only sending the necessary data asynchronously.

What is Ajax?

Ajax is a set of client side technologies that provides asynchronous communication between user
interfaces and web server. So the advantages of using Ajax are asynchronous communication, minimal
data transfer and server is not overloaded with unnecessary load.

What problem does Ajax solve?

In order to answer this question first lets understand how does browser and server work when we request
any website. Below figure depicts pictorially the web environment. When client sends data to the server it
post backs form element data, hidden fields,images,cookie information to the server and server make the
page and sends the same information back to the browser. The bad part this happens with every request
and response.
Below are the issues with the above model:

• Unnecessary data transfers: - In the above model, unnecessary data is transferred between
client and server. For instance, the whole page is posted and refreshed even when we want small
data of the page to be refreshed.
Figure 18.1:- The problem

• Synchronous processing: - When a user requests for a page he has to wait until the complete
round trip happens. In short, the request / response work on a synchronous model rather than
asynchronous which makes user experience very difficult. How many times it has happened that
you are requesting a page and you see the below screen…frustrating right.

Figure 18.2:- Synchronous processing

• Unnecessary processing by server: - Because we are posting unnecessary information to the


server, the server is overloaded with unnecessary processing

Is it possible to use FileUpload control within the update panel?

Yes, it's possible. But we need to use Postback triggers to upload the file.
Which property needs to be set for script manager control to extend the
time before throwing time out expection if no response is
received from the server?

AsyncPostBackTimeout Property needs to set which gets or sets a value that


indicates the time, in seconds, before asynchronous postback time out if no
response is received from the server.

<asp:scriptmanager id="scriptManager1" runat="server"


asyncpostbackerrormessage="We can not serve your request at this
moment.Please try later." asyncpostbacktimeout="36000"></asp:scriptmanager>

The default value of this property is 90 second. We can also set the user defined
error message using asyncpostbackerrormessage property (as shown in above
code) for time out.

What is AJAX

AJAX = Asynchronous JavaScript and XML

AJAX is not a new programming language, but a new technique for creating better,
faster, and more interactive web applications.

With AJAX, a JavaScript can communicate directly with the server, with the
XMLHttpRequest object. With this object, a JavaScript can trade data with a web
server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and
the web server, allowing web pages to request small bits of information from the
server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and more user-
friendly.

You might also like