Explain the basic steps required for creating WCF Service?
1. Create the service
I. Crate the service contract
II. Create the operation contract
III. Implement the service contract
2. Create the endpoints
3. Enable metadata
4. Expose metadata via mex binding or via http get request
5. Host the service
While creating endpoint what all things we need to do?
We have to define the ABC of a service.
- A – Address – Where we get the service
- B – Binding – How to get the service
- What protocol should be used?
- What encoding will be used?
- What security will be applied
- C – Contract –What will be exposed to client.
- What data types will be available for clients?
- What methods (service methods) he is going to get etc
---------------
What are the different contracts available in WCF?
There are five kinds of contracts: -
- Service contracts – Defines the set of operations exposed by the service to the outside world.
- Operation Contract – define the operation within the service contract. In simple technical word service contract is an interface which will be implemented by service and every method in interface is operation contract.
[ServiceContarct]
public interface IMyService
{
[OpearationContract]
void method1(int x);
[OperationContract]
Intmethod2(int x, int y);
}
.
.
.
public class MyService:IMyService
{
public void method1(int x){…}
publicInt method2(intx,int y){…}
}
3. Data Contract –Data to be exchanged between client and service. It’s simply a class
decorated with DataContract attribute and act as an agreement between client and
service quoting “We will pass these things to each other”)
4. Message Contract – In WCF Communication occurs via SOAP messages. Sometimes
developer came across a situation where he want to control how SOAP messages will be
structured. Like what should go into the header? What into the body etc. In this situation
we use Message Contract.
[MessageContract]
public class MyClass
{
[MessageHeader] public intmyProperty1;
[MessageHeader] public DateTimemyProperty2;
[MessageBodyMember] private stringmyProperty3;
[MessageBodyMember] private float myProperty1;
[MessageBodyMember] public DateTime myProperty1;
}
5. Fault contract
- In WCF whenever exception occurs a standard exception error message will returned to client. It look like this

- But sometimes developer want to send customized error then they can use Fault Exception
- We can create custom types and pass error messages to clients using FaultContracts.
[DataContract()]
public class MyException
{
[DataMember()]
public string MyMessage;
}
[ServiceContract()]
public interface IMyService
{
[OperationContract()]
[FaultContract(typeof(MyException))]
intMyMethod(int num1, int num2);
}
.
.
.
Client code
try
{
MyServiceProxy proxy
= new MyServiceProxy();
Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.MyMethod(5, 5));
Console.ReadLine();
}
catch (FaultException<MyException> ex)
{
//Process the Exception
}
publicintMyMethod(int num1, int num2)
{
MyException ex = new MyException ();
ex.MyMessage= "My Error Message”
throw new FaultException<MyException>(ex) ;
}
See following video on WCF (Windows Communication Foundation) endpoints, address, contracts and bindings: -
-----------------
What is known type in WCF?
Normally
when we work with C#, polymorphism work very well. We create a function
which accepts parameter of type1 and while invoking it we will be able
to pass the instance of the one of the derived class of class type1.
Example
public class MyClass{... }
public class MyChildClass:MyClass{…}
.
.
.public class Invoker
{
public void DoSomething(MyClass obj){….}
}
.
.
.
Invoker i=new Invoker();
MyChildClass o=new MyChildClass();
i.DoSomething(o)
In WCF it’s not same. Here we have to define what all substitutions are possible for the datacontract.
If we won’t specify all the substitutions it will throw an exception.
Example
[DataContract()]
public class Customer
{
[DataMember()]
public string CName { get; set; }
[DataMember()]
public string CName2 { get; set; }
}
[DataContract()]
public class GoldCustomer :Customer
{
[DataMember()]
public string CName3 { get; set; }
}
[ServiceContract]
public interface IFirstService
{
[OperationContract()]
string GetData3(Customer c);
[OperationContract()]
string GetData4(GoldCustomer c);
}
FirstServiceClient c = new FirstServiceClient();
GoldCustomer mycust = new GoldCustomer();
mycust.CName = "Sukesh";
mycust.CName2 = " Marla";
Console.WriteLine(c.GetData3(mycust));

How to provide substitutions
We use knowtype attribute for that.
[KnownType(typeof(GoldCustomer))]
[DataContract()]
public class Customer
{
[DataMember()]
public string CName { get; set; }
[DataMember()]
public string CName2 { get; set; }
}
Once the knownType is attached code will work.
For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on REST (Representational state transfer): -
------------------
What are the different Security modes available in WCF (Windows Communication Foundation)?
There are three different Security modes available in WCF (Windows Communication Foundation)
- Message – here Message itself get encrypted and signed. By default authentication option are windows but supports wide variety of client credentials including customer UserName and Password validation. It will be slower in performance, but support for wide variety of client credentials makes it a good option too.
- Transport – here Message will be transferred as a plain text but the transport which passes that data will be secured. In this mode binding leverages the security feature provided by transport like SSL. Its good performance makes it a better option but less support for different client credentials makes it bad choice.
- Mixed – This is a mode where advantages of both the world will be used.Data will be protected with the help of transport and thus providing better performance plus supports wide variety of user credentials.
For
technical trainings on various topics like WCF(Windows Communication
Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and
Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on create the service using WCF (Windows Communication Foundation): -
--------------------------
Tell me something about PerSession instance context mode in WCF?
When
we set instance context mode as PerSession in WCF, for every channel
object or proxy object client creates a dedicated service instance will
be created.
What happens by that?
Our service become state full. Values of the variables updated during subsequent service call will be maintained.
Is it the default instance context mode?
Yes
it is, considering binding supports session full endpoints. For example
when your binding is netTcpEndpoint or wsHttpBindingPerInstance is
default but when its basicHttpBinding default one will be percall
because PerInstance is not supported over there?
Does WsHttpBinding supports sessions all the time?
No, it supports only if security is enabled. Best point is in case of WSHttpBinding security is be default turned on.
What if I don’t want security but wants session?
You have to enable reliable messaging at least. Reliable messaging is not enabled by default.
How the server differentiates between different sessions in case of per instance?
It
will be with the help of sessionId. SessionId will be created for a
client when he create the proxy or channel instance for first time.
Is it possible to get current session Id in service?
Yes, using OperationContext.Current.SessionId
For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on WCF concurrency and throttling: -
What all things need to remember while implementing security in a service?
Service
means exposing business functionality. Exposing business functionality
always includes exchange of data and protecting data is equally
important. When it comes to protecting data we have to consider
following three things: -
1. Whatever data is exchanged can only be understood by proper recipient. Even if
somehow unintended recipient gets access to data, he or she should not be able to read
it. In terms of service protection this is called as “Confidentiality”.
2. Whatever sender sends, receiver receives it. Let say an intruder comes in between and
modifies the data. When data reaches the receiver it should reject it and throw an
exception. In simple words data should not be tempered. In terms of service protection we
call it “Integrity”.
3. Every user should be validated for his/her identity. In terms of service protection that is
called authentication.
For
technical trainings on various topics like WCF(Windows Communication
Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and
Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on create the service using WCF (Windows Communication Foundation): -
--------------------
How to invoke WCF service asynchronously?
As
a service developer we just simply create the service, host it and
expose the endpoints. Now whether those functions should be called
synchronous or asynchronously is client’s lookout.
When
the proxy class of our service get generated in the client side, async
version of all our service methods also get generated automatically.
For
example : If our service contain methods such as GetString, GetCustomer
then our proxy class will contain four methods,
GetString,GetCustomer,GetStringAsync,GetCustomerAsync.
There are two approaches normally a .net developer can follow,
1. Event based approach
2. Task based approach
1. Event based approach
Both
the asynchronous methods will never return anything. Return type will
be void. Instead on completion, some events will be raised.
Complete code:
privatevoid button1_Click(object sender, EventArgs e)
{
FirstClient c = newFirstClient("WSHttpBinding_IFirst");
c.GetStringCompleted += c_GetStringCompleted;
c.GetStringAsync();
.
.
}
.
.
.
.
voidc_GetStringCompleted(object sender, GetStringCompletedEventArgs e)
{
label2.Text = e.Result;
}
2. Task based approach
In
this approach C# 5.0 asycn await pattern will be used. Here
asynchronous methods will return “Task” object instead of direct return
value which can be awaited later
privateasyncvoid button1_Click(object sender, EventArgs e)
{
FirstClient c = newFirstClient("WSHttpBinding_IFirst");
Task<string> r=c.GetStringAsync();
.
.
.
label2.Text += "\n" + await r;
}
For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on WCF concurrency and throttling: -
-----------------
How we can achieve these in WCF?
In case of WCF client access the service via endpoint exposed by service. Endpoint composed of Address, Binding and Contract.
Out of these, binding defines: -
- What kind of security should be implemented
- What kind of encoding should be used etc?
In
wsHttpBinding and netTCPBinding security will be enabled by default. It
makes sure that all three aspects of security are achieved.
If you want to read more about WCF Security click herehttp://dotnetinter.livejournal.com/99037.html
For
technical trainings on various topics like WCF(Windows Communication
Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and
Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on create the service using WCF (Windows Communication Foundation): -
------------------
How security works in WCF?
In WCF security is by default enabled in wsHttpBinding and NetHttpBinding.
Enabled means all three aspects of security (CIA) is automatically provided by bindings.
Let’s understand how.
1. C – Confidentiality – Data can be viewed by only intended recipient.
It is done by means of encryption. Data (Messages) to be transferred will be encrypted.
Even if someone get the message he will not be able to understand it.
2. I – Integrity – Data should not be tempered.
It is done by means of signing. Data (messages) to be transferred will be signed.
If someone modifies the data in between receiver easily come to know about that.
3. A – Authentication – User should validate his/her identity.
By default all the binding except basic provides windows authentication. It means every
service call will be authenticated automatically. While making call automatically clients
windows credentials will be passed along which will be automatically get validated in
service end. In case he is not a valid AD – Active directory user, his/her request won’t get
processed.
For
technical trainings on various topics like WCF(Windows Communication
Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and
Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on WCF(Windows Communication Foundation) Concurency and throttling: -
-------------------
What is instancing in WCF?
WCF
Instancing let us control the instance creation behavior of the
service. It simply describes how many objects should be created of a
service.
Confused!!!!
Here
one may ask a question. “We are the one who create the object in the
client side that means we have complete control over object creation,
then how this is different from WCF instancing?”
Well, let’s understand this.
We
won’t create the object of service in client side. If you think
properly then you will realize that we create the object of service
proxy class (generated at the client place, when we say add reference).
We use this object and invoke service methods. In that very moment at server side service instance get created.
WCF instancing let us control this object creation behavior.
Instancing modes
There are three modes of instancing available: -
- Per call – With every service call one instance will be created.
- Per instance –for one proxy object one instance will be created
- Single – Only one object will be created throughout.
See the following video on REST (Representational State Transfer): -
--------------------
What different Message Exchange Patterns are available with WCF?
Message exchange pattern describes how client and Service exchange messages with each other.
In
simple words it let us answer, Client will send a request to service
but what after that, will client wait for the response or just continue
with the flow.
There are three Message exchange patterns.
1. One Way
In this pattern client send make a call to service and just continue with its flow. It won’t wait for result to come back.

2. Request Response
In this pattern client will send a request to service and wait for response to come back

3. Duplex
In
this pattern, a two way channel will be created. Client will send a
request using this channel and continue with it operation. It won’t wait
for service to complete its operation.
When service completes its operation, it will invoke callback method in the client.

For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
Click and see here http://www.questpond.com/ for more training on WCF(Windows Communication Foundation).
--------------------
Serialization events
In
case of DataContractserialzier, during serialization and
deserialization constructor won’t get invoked. However
DataContractserializer supports callbacks which we can use for
initialization.
These callbacks works with the help of some special attributes
- OnDeserializedAttribute– Marks method to be invoked immediately after the object is deserialized.
- OnDeserializingAttribute – Marks method to be invoked during deserialization of an object.
- OnSerializedAttribute– Marks method to be invoked immediately after the object is Serialized.
- OnSerializingAttribute – Marks method to be invoked during Serialization of an object.
[DataContract]
public class MyData
{
[DataMember]
publicintdata1;
[OnDeserialized]
voidOnDeserialized(StreamingContext c)
{
}
[OnDeserializing]
voidOnDeserializing(StreamingContext c)
{
}
[OnSerialized]
voidOnSerialized(StreamingContext c)
{
}
[OnSerializing]
voidOnSerializing(StreamingContext c)
{
}
}
For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on WCF(Windows Communication Foundation) One way contract: -
-------------------
What is the difference between data contract serializer and XML serializer?
XML Serializer
- It follows the Opt-out approach. It means all the public properties get serialized. If you don’t want something you have to specify explicitly.
- It serializes only properties and again only public properties with both get and set accessor.
Data contract serializer
- It follows Opt-In approach. It means we have to explicitly specify what we want to serialize.
- It can serialize nonpublic members and fields also.
For
technical trainings on various topics like WCF, MVC, Business
Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free
to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
For more stuff like this, click here http://www.sukesh-marla.com/. Subscribe to article updates or follow at twitter @SukeshMarla
See following video on endpoints, address, contracts and bindings: -
---------------------
What is the difference between Service and endpoint in WCF?
Service: means self-contained business functionality. It encapsulates the business logic which clients invoke.
Endpoint: Defines
the communication options. Every service exposes one more endpoints
using which client uses for invoking service methods.
What is service behavior?
Service
behavior let us control the behavior of the service. Behavior such as
whether metadata should be published or not? How many concurrent calls
are possible for a service? Etc.
How to make enable metadata publishing in service?
Add this block inside servicemodel tag in web.config

It will enable metadata for all services.
Why client need access to this metadata and how client get access to it?
From
the Metadata client comes to know about the endpoints defined in the
service. In which he/she will use for interacting with such service.
He
will get access to this metadata as a WSDL document. Client will get
the WSDL document by making get request to service or via mex endpoint.
--------------
Explain WCF service model architecture?
- In the first step client gets the information about the endpoints of a service via service metadata.
- Once client have the meta data of a service he will get all the knowledge of a service like what all things can be achieved from service (What functionality service exposes), What data type it expects, What it returns etc.
- In case of WCF Service that metadata contain information about endpoints.
- Client will constructs the channel based on the endpoint of its interest.
- Client using this endpoint sends messages to service.
How the service metadata will be exposed to client?
Mostly
it will be via WSDL but in case of WCF we can expose mex endpoint which
will expose metadata containing other endpoint information.
How metadata get created in WCF?
In WCF world if the SeviceMetadata behavior is enabled for service this Metadata will get created automatically.
Can you explain more about Mex and WSDL?
ServiceMetadata
behavior contain an attribute called httpsGetEnabled, if this property
is set to true we will be able to get the Metadata using get request.
Get request to WSDL file which will be usually located in the same
service url with an additional suffix of “?WSDL”
With Mexennpoints we get an ability to obtain service metadata via SOAP messages instead of http Get.
Best part about mex is it makes metadata available via various transports like HTTP, TCP etc.
--------------------
What is WCF and how it is different?
WCF is Microsoft’s platform for building SOA based applications.
With Microsoft web services building SOA based application was trouble. Webservices won’t support all WS-* specifications.
In Microsoft world,
- Webservices only work with HTTP. If we want to work with TCP only option left will be Remoting.
- For transaction based operations (if one operation all previous operations should be rolled back) we have to rely COM+
- Com+ and Remoting used to work only with Microsoft technologies. Application written in Java will not be able to talk via these methodologies.
WCF is a unification of Webservices, Remoting and Com+.
A
platform independent mechanism but supports transaction, multiple
protocols, and other features specified by ws-* specification.
What is mean by WS-* specification?
WS-*
specification are standards and specifications defined for web
services. It has many specification like WS-security – which will
describes how security will be handled with SOAP messages,
WS-transaction - how multiple services work in transaction etc.
---------------
What is Service Oriented Architecture?
Service
oriented architecture (SOA) or WCF(Windows Communication Foundation) is
an architectural style for building business application consisting
services. It will be completely independent of technology and
environment.
What do you mean by Service? I mean to say can we call every business logic a service? What guidelines we need to follow?
- It’s self-contained business functionality. It will do everything we want. Client will not rely on multiple services or multiple business blocks in order to do one Unit of Work
- It will independent from all other services.
- It should be self-descriptive. It should answer client what all operations it has and what are the data types it accepts etc.
- Client should be able to invoke them asynchronously if required.
- They should support secure communication.
- Communication with them should be done via standard messages. A standard message means platform and technology independent messages.
---------------
What are the different ways of doing WCF concurrency and WCF instancing?
WCF concurrency
There are 3 ways of configuring WCF concurrency.
Single:
- A single request has access to the WCF service object at a given
moment of time. So only one request will be processed at any given
moment of time. The other requests have to wait until the request
processed by the WCF service is not completed.
Multiple:
- In this scenario multiple requests can be handled by the WCF service
object at any given moment of time. In other words request are processed
at the same time by spawning multiple threads on the WCF server
object. So you have great a throughput here but you need to ensure
concurrency issues related to WCF server objects.
Reentrant:
- A single request thread has access to the WCF service object, but the
thread can exit the WCF service to call another WCF service or can also
call WCF client through callback and reenter without deadlock.
WCF concurrency is configured by using concurrency mode attribute as shown in the below figure.

WCF instancing
Per Call: - New instance of WCF service are created for every call made by client.
Per session: - One instance of WCF service is created for a session.
Single instance: - Only one instance of WCF service is created for all clients.
To configure WCF instancing we need to use the InstanceContextmode attribute on the service as shown below.

--------------
What is WCF?
WCF is s Microsoft's platform for building SOA based applications.
What is SOA?
SOA is architectural styles where application will be built considering services as the main entity.
What are Services?
Services
are self contained business functionality. Every service encapsulates
one unit of work and every service will b independent of other.
How to pass data to service and how to get data from service?
Data will be sent and received from service in terms of Messages. Messages will b standard across all technologies.
How WCF service is different from web service?
Web service won’t support all WS-* specifications where as WCF service does that.
--------------
Explain WCF Duplex services? ( WCF Interview questions)
June 7, 2014 at 3:29pm
In case you fresher to WCF start with www.questpond.com video on WCF fromhttp://www.youtube.com/watch?v=pVYomdwJWls
This is a message exchange pattern where both client and server have the ability to send messages to each other.
In
Duplex communication Client connects to a service and provides the
service with a channel using which server can send messages back to
client.
How it works?
In order to make this work we need a pair of interfaces,
- First interface will be your service contract which contains operation contracts which client can invoke.
- Second interface contain operations which will act as a call back method for server. In simple words, contain methods which can be invoked by server.
How server contract come to know about Callback interface?
In the service contract attribute we specify the callback interface as follows.
[ServiceContract(CallbackContract=typeof(IClientCallback))]
What about the client? I mean, after client implement the interface how it provide the actual instance?
It can be done via overloaded version of proxy class created at client side.
public class ClientCallBack : IClientCallback
{…..
InstanceContext instanceContext = new InstanceContext(new ClientCallBack ());
// Create a client
MyServiceClient client = new MyServiceClient (instanceContext);
At Server side, how callback methods will be accessed?
Using OperationContext class as follows,
OperationContext.Current.GetCallbackChannel<IClientCallback>().CallBackMethod();
--------------
What exactly do you mean by Single in WCF instancing? How to set and what is by default set value of instance context mode?
When
we specify Instance context mode of our WCF service as single, it makes
only one instance context object is used for all incoming request. It
works like this,
- When the very first request is made, object will be created and will be never destroyed.
- For all further requests same object will be reused.
One
of the biggest problems with this mode is, if exception/errors are wont
handled properly; one service call failure may affect other calls as
well.
How to set instance context mode?
We have to set it above the service class using Service behavior attribute.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
……….
}
What is the by default Instance Context Mode?
By default, it is set as Per Call.
------------
No comments:
Post a Comment