Friday, 27 September 2013

WCF(Window Communication Foundation) Interview Question & Answers


1. What is WCF ?
  • Stands for Windows Communication Foundation.
  • Its code name is “Indigo”.
  • It is a framework for building, configuring and deploying interoperable distributed services.
  • It enables you to write more secure flexible services without any code change (using configuration).
  • It also provide built-in support for logging. You can enable/disable logging using configuration.
WCF = Web Service + Remoting + MSMQ + COM+
(or)
WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services

2. What is Contract ? What are the types of Contract ?

It is the agreement between client and service which specifies:

  • [ServiceContract] - which services are exposed to the client.
  • [OperationContract] - which operations the client can perform on the service.
  • [DataContract] – which data types are passed to and from the service.
  • [MessageContract] - allow the service to interact directly with messages. Message contracts can be typed or untyped and are useful in interoperability cases when another party has alreadydictated some explicit (typically proprietary) message format.
  • [FaultContract] -which errors are raised by the service and how the service handles andpropagates errors to its clients.

3. Difference between WCF and ASP.NET Web Service

Here are the 10 important differences between WCF Services and ASP.NET Web Services:

4. What are the transport schemes supported by WCF ? Give example of address for each scheme.

Following are the transport schemes supported by WCF:


  • HTTP/HTTPS - http://localhost:8001/MyService
  • TCP - net.tcp://localhost:8002/MyService
  • IPC - net.pipe://localhost/MyPipe
  • Peer network
  • MSMQ - net.msmq://localhost/private/MyQueue
  • Service bus - sb://MyNamespace.servicebus.windows.net/

5. What is binding ?

A binding is the set of configurations regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability.


6. What are the types of bindings supported by WCF ? What are their advantages and disadvantages ?

BindingFeatureSuitable ForTransportMessage encodingSecurity ModeResource ManagerTransaction Flow
BasicHttpBindingNot secure by default.Communication with WS-Basic Profile conformant Web Services like ASMX.HTTPTextNoneXX
WSHttpBindingSecure, Interoperable.Non-duplex service contracts.HTTPTextMessageDisabledWS-Atomic
WSDualHttpBindingSecure, Interoperable.Duplex service contracts or communication through SOAP intermediaries.HTTPTextMessageEnabledWS-Atomic transaction
WSFederationHttpBindingSecure, Interoperable.Supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.HTTPTextMessageDisabledWS-Atomic transaction
NetTcpBindingSecure, Optimized.Cross-machine communication between WCF applications.TCPBinaryTransportDisabledOle transaction.
NetPeerTcpBindingSecure.Multi-machine communication.P2PBinaryTransportXX
NetNamedPipesBindingSecure, Reliable, Optimized.On-machine communication between WCF applications.Named PipesBinaryTransportXOle transaction.
NetMsmqBindingCross-machine communication between WCF applications.MSMQBinaryMessageXX
MsmqIntegrationBindingDoes not use a WCF message encoding – instead it lets you choose a pre-WCF serialization format.Cross-machine communication between a WCF application and existing MSMQ applications.MSMQPre-WCF formatTransportXX

7. What is Endpoint in WCF ?

Endpoint = Address (A) + Binding (B) + Contract (C)
Address specifies where the services is hosted.
Binding specifies how to access the hosted service. It specifies the transport, encoding, protocol etc.
Contract specifies what type of data can be sent to or received from the service.
Eg:
<endpoint name="BasicHttpGreetingService" address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding" contract="MyNamespace.MyService.IGreetingService" />

8. Explain Address in detail ?

It is the url which specifies the location of the service. Client can use this url to connect to the service and invoke the service methods.

Eg: http://localhost:5487/MyService/GreetingService.svc

9.  Explain Binding in detail ?

It specifies how to access the hosted service. There are following characteristics of binding:
Transport defines the communication protocol to be used to communicate between service and client. It may be HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to define transport.
Encoding defines the technique used to encode the data before communicating it from one end to the other.
Protocol defines the configurations like reliability, security, transaction, timouts, message size etc.

10. What is binding configuration ?

You can customize the binding used by endpoint using config file. For example, you can enable/disable transaction for the binding used by endpoint. All you need is to configure binding element in config file similar as below:
<bindings>
  <netTcpBinding>
    <binding name = "TransactionalTCP" transactionFlow = "true" />
  </netTcpBinding>
</bindings>

11. What is default endpoints ?

If the service host does not define any endpoints (neither in config nor programmatically) but does provide at least one base address, WCF will by default add endpoints to the service. These are called the default endpoints. WCF will add an endpoint per base address per contract, using the base address as the endpoint’s address. WCF will infer the binding from the scheme of the base address. For HTTP, WCF will use the basic binding. Note that the default bindings will affect the default endpoints. WCF will also name the endpoint by concatenating the binding name and the contract name.

12. How can we enable/disable metadata publishing of our WCF service ?

You can enable enable meta data publishing for a WCF service two ways:
  • Configure metadata publishing for a service that uses default endpoints. Specify the ServiceMetadataBehavior in the configuration file but do not specify any endpoints.
<configuration>
 <system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
         <serviceDebug includeExceptionDetailInFaults="False" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
  • Configure metadata publishing for a service that uses explicit endpoints. Specify the ServiceMetadataBehavior in the configuration file and a mex endpoint.
<configuration>
 <system.serviceModel>
   <services>
     <service name="MyNamespace.MyService.GreetingService" behaviorConfiguration="CustomServiceBehavior">
       <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.MyService.IGreetingService" />
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
   </services> 
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
Supported bindings for mex endpoint are mexHttpBindingmexHttpsBindingmexNamedPipeBinding andmexTcpBinding.

13. How can you generate proxy class and configuration file for WCF service ?

WCF provides an utility svcutil.exe which can be used to generate proxy class and configuration file. Eg:
SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig

14. Is there any tool provided by Microsoft for editing configuration file ?

Yes. Microsoft provides an utility “SvcConfigEditor.exe” that can edit any configuration file.

15. How can you test your new WCF service without writing any client application ?

Microsoft provides a tool which can be used to test any WCF service. To use this tool, open visual studio command prompt and execute the command “wcftestclient.exe“. It will open a window where you can add many WCF services and test. You can also provide values for input parameters of WCF methods.

16. Which bindings support reliability and message ordering ?

Binding nameSupports
reliability
Default
reliability
Supports ordered
delivery
Default Ordered
delivery
BasicHttpBindingNoN/ANoN/A
NetTcpBindingYesOffYesOn
NetNamedPipeBindingNoN/A(On)YesN/A(On)
WSHttpBindingYesOffYesOn
NetMsmqBindingNoN/ANoN/A

17. How can you configure reliability using .config file ?

<bindings>
  <netTcpBinding>
    <binding name = "ReliableTCP">
      <reliableSession enabled = "true"/>
    </binding>
  </netTcpBinding>
</bindings>

18. How to create a service contract and operation contract ? Can you give an example ?

We can create a contract using an interface by applying [ServiceContract] and [OperationContract] attributes on Interface and Methods respectively.
[ServiceContract]
public interface IGreetingService
{
    [OperationContract]
    string GreetMe(string userName);
}

public class GreetingService : IGreetingService
{
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}
If we do not want to create interface then we can apply the attributes on a class itself.
[ServiceContract]
public class GreetingService
{
    [OperationContract]
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}

19 . Can you give an example of DataContract ?

[DataContract]
public enum Color
{
  [EnumMember]
  Red,

  [EnumMember]
  Green,

  [EnumMember]
  Blue
}
[DataContract]
public class Shape
{
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public Color FillColor { get; set; }

  [DataMember]
  public double Area { get; set; }
}

20. What is MessageContract ? Can you give an example ?

WCF uses SOAP messages to transfer information from client to server and vice-versa. It converts data contract to SOAP messages. SOAP message contains Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Header contains important information which are related to communication but not directly related to message. SOAP body contains information which is used by the target.

SOAP Envelope = Name + Namespace  + Header + Body
However there are some cases when you want to have control over the SOAP messages. You can achieve this using MessageContract.

[MessageContract]
public class Shape
{
    [MessageHeader]
    public string ID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public double Area;
}
In above example, ID will be added as header, Name and Area as body in SOAP envelope.
When you use MessageContract then you have control over the SOAP message. However some restrictions are imposed as below:
  • You can have only one parameter for a service operation if you are using MessageContract.
  • You can return either void or MessageContract type from service operation. Service operation can not return DataContract type.
  • Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
  • You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property.
  • The order of the body elements are alphabetical by default. But you can control the order, using Order property in the MessageBody attribute.

21. What is FaultContract ?

In most of the cases you would like to convey the details about any error which occurred at service end. By default, WCF exceptions do not reach client. However you can use FaultContract to send the exception details to client.

[DataContract()]
public class CustomError
{
  [DataMember()]
  public string ErrorCode;
  [DataMember()]
  public string Title;
  [DataMember()]
  public string ErrorDetail;
}

[ServiceContract()]
public interface IGreetingService
{
  [OperationContract()]
  [FaultContract(typeof(CustomError))]
  string Greet(string userName);
}

public class GreetingService : IGreetingService
{
  public string Greet(string userName)
  {
    if (string.IsNullOrWhiteSpace(userName))
    {
        var exception = new CustomError()
        {
            ErrorCode = "401",
            Title = "Null or empty",
            ErrorDetail = "Null or empty user name has been provided"
        };
        throw new FaultException<CustomError>(exception, "Reason : Input error");
    }
    return string.Format("Welcome {0}", userName);
  }
}

22. What are session modes in WCF ? How can you make a service as sessionful ?

ServiceContract attribute offers the property SessionMode which is used to specify the session mode. There are three session modes supported by WCF:
  • Session.Allowed(default): Transport sessions are allowed, but not enforced. Service will behave as a per-session service only if the binding used maintains a transport-level session.
  • Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
  • Session.NotAllowed: Disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, the service will always behave as a per-call service. 
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{...}



Tuesday, 24 September 2013

ADO.NET INTERVIEW QUESTIONS & ANSWERS


1. What is ADO.NET ? 

ADO.Net is one of the major component of .Net Framework, which is designed to connect to databases like Oracle, MySQL, SQL Server, MS Access etc. and work with data stored in them.


2. Explain Generic Features of ADO.Net ?

  • ADO.Net provides in built classes to connect with Databases like Oracle, MySQL, SQL Server, MS Access etc.
  • Provides in built classes to do data manipulation operations like Insert, Update, Delete and Select Data.
  • Provides data providers for specific databases for efficient interactions with DB. Example ODP.Net provider for Oracle.
  • Tight integration with XML
  • Provides functionality to combine data from different data sources
  • Disconnected Data architecture for better performance

3. What are the important features of ADO.Net 2.0 ?

Bulk Copy Operation from one Data Source to another Data Source 

  • Batch Update – To update no of rows in a table in a single call from a program thus by avoiding round trip to database.
  • Data Paging – To read data from a certain index
  • Connection Details – To get detailed info about connections like buffer information,cursor details etc
  • DataSet.RemotingFormat Property – To make dataset serialized in Binary
  • DataTable's Load and Save Methods – For XML interactions.

4. What are the namespaces used in ADO.NET for data access ?



Namespaces used to access database are

  • System.Data – Contains all generic data access classes
  • System.Data.Common – Contains classes which are shared / overridden by data providers
  • System.Data.OleDb - OLE DB provider classes used to access database such as Oracle, MySQL, SQL Server and MS Access.
  • System.Data.SqlClient – Contains classes for SQL Server
  • System.Data.SqlTypes – Contains SQL Server data types
5. What are major difference between classic ADO and ADO.NET ?
ADO
  • ADO have recordset
  • ADO objects communicate in binary mode.
  • ADO Supports mostly Connection oriented Models
  • Since ADO derives information about data implicitly at run time based on metadata , it is an expensive process.
  • Only Client Side Cursors are allowed in ADO.

ADO.Net
  • ADO.Net have Data Adapter and Data set
  • ADO.NET uses XML for passing the data.
  • ADO.Net works in Disconnected manner
  • By leveraging known meta data at design time, ADO.Net provide better runtime performance and more consistent runtime behaviour
  • ADO.Net Support both client side and server side cursors

6. What are the two fundamental objects in ADO.NET ?
Fundamental Objects of ADO.Net are DataReader and DataSet . DataSet Object can have a set of DataTables, relationships between these tables. DataSet can be used in disconnected connection with DB. DataReader is used to read the read only data from a database.
7. What is difference between dataset and datareader ?
DataReader is used to fetch data from a database in a much faster way. Since the rows are fetched one at a time, load on the network will be low. Since DataReader is read only, transactions are not allowed . Since it is forward only, random data fetch is not supported.
DataSet is an in memory representation of a tables in a database. Dataset takes lot of application memory compared to DataReader. Its slower compared to DataReader. But user can do transactions using DataSet. It also support querying.
8. What is the use of connection object ?
Connection Objects is used to establish a connection between an application and databases like Oracle, MySQl, SQL Server etc. Once connection is established, SQL Commands like insert, update, delete and select can be executed. Scope of a connection object can be local or global. If local connection object is used, it should be closed after SQL commands are executed.
9. Explain ReadCommitted and ReadUncommitted in Transactions ?
All simple Transcations are ReadCommitted by default. If two persons are accessing same table, if one persons executes an insert , other person will be able to access the newly inserted row only after the first person commit the transaction. If a transaction is set as ReadUncommited, in the two person scenario, second person will be able to read the information inserted by first person before he commits the transaction.
10.  What is a Dataset object ?
The DataSet is used to store data from a data source . It consists of a set of data tables. We can also specify the relation between the tables inside a dataset.
11. What is a Datatable object ?
Data Table is used to store the data retrieved from a database in application memory. Data table will have a set of data columns and data rows. Data table supports operations like adding, updating and deleting a row.
12. What are the different execution methods provided by the command object ?
After creating an SQL or OLEDb Command, it needs to be executed. Following methods are used to execute SQL Commands.


  • ExecuteNonQuery() – Used to execute the command which did not return any output
  • ExecuteReader() – Used to execute the command and return a typed IDataReader
  • ExecuteScalar() – Used to execute the commands that return a single value
  • ExecuteXmlReader() – Used to execute the command that returns an XmlReader object. The object can be used to traverse the XML fragment returned from DB.



13. What is the use of data adapter ?

To populates tables within a dataset from a data source, DataAdapter is used. DataAdapter uses ADO.Net Connection object to connect to a data source. It uses Command Objects like Insertcommand, UpdateCommand and DeleteCommand to make changes to a data source.
14.  What’s difference between “Optimistic” and “Pessimistic” locking ? 
Pessimistic locking is used when user wants to update a record in a database and the user want to prevent other users from updating the same record. Other user’s can only view the data when there is pessimistic locking. In optimistic locking is used to improve concurrent operations on a record by allowing multiple users to update the same record. Record is only locked when updating the record. Optimistic locking has been widely used by web developers.
15. What’s difference between Dataset. clone and Dataset. Copy ?
Dataset.Clone only copies the schema of a DataSet object like relations between data tables and constraints. Dataset.Copy copies both the data and structure of a DataSet object.
16.  What is Maximum Pool Size in ADO.NET Connection String ?
Default max pool size is 100. When an application requests for connection from a pool , if the connections are free, pool will return a free connection. If all the connections are in use and connection pool max size is not reached , pool will create a new connection and send it to the application. When a request for new connection arrives and If the max pool size is reached and all the connections are busy, it will be made to wait till one of the existing connection get released back to pool.
17. How to enable and disable connection pooling ? 
Use Pooling = true in connection string , if we want to enable connection pooling. To disable connection pooling set Pooling = false .
18. What is LINQ ?
Language-Integrated Query (LINQ) is one of the advanced featured provided by .Net. LINQ provides native query language for C# and VB.Net to update and retrieve data from different data sources like SQL Server Database,XML etc.
19.  What is the difference between Command and CommandBuilder object ?
Command is used to execute all kind SQL queries like data manipulation languages (DML) and Data definition language(DDL) . DML operations are SELECT, INSERT, UPDATE, and DELETE . DDL operations are Create and drop tables. Command Builder object is used to build and execute DML queries like select, insert and delete table.
20.  What are the methods of XML dataset object ?
Different methods of XML dataset object:
  • ReadXml(Stream) – Uses System.IO.Stream to read XML schema and data into the DataSet
  • ReadXml(String) – Reads XML data from the specified file.
  • ReadXmlSchema() – Reads XML schema from the specified file.
  • GetXml() – Get XML data in a Dataset as a single string.
  • GetXmlSchema() – Get XSD Schema in a Dataset as a single string.
  • WriteXml() – Writes the contents of Dataset to the specified file.
  • WriteXmlSchema() – Writes XSD Schema into the specified file.
21.  What are different layers of ADO.Net? 
  • Database Access Layer
  • Business Logic Layer
  • Presentation Layer
22. What is the difference between typed and untyped dataset ?
Typed datasets have and associated schema file. Error checking will be done during design time with respect to schema. It also use explicit names and data types for their members . Untyped dataset uses table and column collections for their members. There wont be any error checking associated with Untyped Dataset, since they are populated at runtime.
23. Which object is used to add relationship between two Datatables ?
DataRelation object is used to add relationship between two or more datatable objects.
24. What are the parameters that control most of connection pooling behaviors ?
  • Max Pool Size – Maximum size of connection pool
  • Min Pool Size – Minimum no of connections that will be created in connection pool at application start up.
  • Pooling – To set connection pooling to on or off.
  • Connect Timeout – Wait period for new connection.