Sunday, 27 May 2012

FAQ's - WCF (Windows Communication Foundation)

What is WCF?

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment 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.
 
ABC is the three building blocks of WCF and they are known as

A - Address (Where): Address tells us where to find the services, like url


B - Bindings (How) : Bindings tells us how to find the services or using which protocols finds the services (SOAP, HTTP, TCT etc.)

C - Contacts (What): Contracts are an agreement between the consumer and the service providers that explains what parameters the service expects and what return values it gives.

Hope this will be very helpful to understand three building blocks of WCF, a very frequently asked interview questions.
 
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 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 contains 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 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 we can 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 and when there is an existing message format we have to comply with.
 
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 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 being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, 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 work with 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, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to 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 subscribe to 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 secure binding 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 reliability, 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 service to 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 interoperate with legacy MSMQ clients.

For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx
 
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 defines 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.


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 WebGet Attribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
 
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 on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
 
 
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 as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service 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 to 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 metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch 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 base address:

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

 
What are different elements of WCF Srevices Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like


   

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

         binding  = "wsHttpBinding"

         contract = "IMyContract"

      />

   


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 order of 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 reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

How to configure Reliability while communicating with WCF Services?
 
Reliability can be configured in the client config file by adding reliableSession under binding tag.


   

      

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

            binding  = "netTcpBinding"

            bindingConfiguration = "ReliableCommunication" 

            contract = "IMyContract"

         />

      

   

   

      

         

             

         

      

   


Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding


 
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.

...
binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
...
/>





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 attribute, we 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 client proxy will have two methods with different name AddInt and AddDouble.
 

Thursday, 24 May 2012

FAQ's - ASP.NET MVC

What are the 3 main components of an ASP.NET MVC application?

“ASP.NET MVC is the evolution of Classic ASP, adding an easier separation of concerns while not using an event based model like WebForms.”
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?
System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC

What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5
Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

Explain different return types in controllers?


ActionResult is an abstract class that can have several subtypes:

a) ViewResult - Renders a specifed view to the response stream
b) PartialViewResult - Renders a specifed partial view to the response stream
c) EmptyResult - An empty response is returned
d) RedirectResult - Performs an HTTP redirection to a specifed URL
e) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
f) JsonResult - Serializes a given ViewData object to JSON format
g) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
h) ContentResult - Writes content to the response stream without requiring a view
i) FileContentResult - Returns a fle to the client
j) FileStreamResult - Returns a fle to the client, which is provided by a Stream
k) FilePathResult - Returns a fle to the client

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

Difference Between ViewBag and ViewData in MVC 3?

View Data
View Bag
ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:
ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:
In Controller

public ActionResult Index()
{
    var softwareDevelopers =
new List<string>
    {
       
"Brendan Enrick",
       
"Kevin Kuebler",
       
"Todd Ropog"
    };

    ViewData[
"softwareDevelopers"] = softwareDevelopers;

   
return View();
}
In View
<ul>
@foreach (var developer in (List
<string>)ViewData["softwareDevelopers"])
{
   
<li>
        @developer
   
li>
}
ul>
Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.
In Controller

public ActionResult Index()
{
    var softwareDevelopers =
new List<string>
    {
       
"Brendan Enrick",
       
"Kevin Kuebler",
       
"Todd Ropog"
    };

    ViewBag.softwareDevelopers = softwareDevelopers;

   
return View();
}

In View
<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
   
<li>
        @developer
   
li>
}
ul>
Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.



Difference Between ASP.NET WebForms and ASP.NET MVC?
ASP.NET WebForms
ASP.NET MVC
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain
The View is called before the Controller.Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.ASP.NET MVC does not maintain state information by using view state
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application developmentWorks well for large projects where focus in on testability and maintainability.

Wednesday, 23 May 2012

FAQ's - JQuery


If you put jQuery in your CV, then beware, you should be able to answer following questions. Better you read on, and test yourself how much you can score.

1. What is jQuery & its significance? Why it is so popular?


jQuery is lightweight, client side script JavaScript library file that supports all browsers.JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery makes it easy to play with the DOM, add effects, and execute Ajax requests.

This helps developer to reduce lines of code while he/she program. For example huge code written in Java Script, can be done easily with JQuery in one or two lines as it uses pre compiled JavaScript library internally. For example To find a Div that have class xxx we can do this using custom JavaScript by looping through all DOM elements, Find Div element write if statement checking the class then write the code to manipulate cross browser.  But this can be achieved using jQuery with 2 lines of code. jQuery is a fun library to use and play.

It is so popular due to the below 10 reasons.
  • Cross Browser Compatibility.
  • Fast but micro Famework.The jQuery core library minified is only about 24KB in size, so it is very easily to include in any application and it is pretty fast as well.
  • Easy to learn and flexible.
  • It is well documented.
  • Reuse of plug-ins across projects .These plug ins are extendable.
  • Latest CSS Complaint.
  • Microsoft, which now includes jQuery with its MVC framework and integrated to VS2010 with intellisense support .
  • IBM, Netflix use jQuery. Nokia have adopted it. Google uses and hosts the jQuery library.
  • Easy to find support since there is a large development community and variety of plug-ins.
  • DOM manipulation with querying and chaining is Wonderful & Robust. It is simple, concise and clear enough.
Hence jQuery is definitely faster, easier and more productive than previous traditional JavaScript that we use, hence its so popular.
Now the Client side development is fun using jQuery Agree or not ??

2. What is jQuery UI?

jQuery UI  is a library which is built on top of JQuery library.  It can be called as one of the JavaScript plug-in that allows to create animations, sortables list, draggle list . This is developed as separate JavaScript File. This can be downloaded from http://ui.jquery.com/download (ui.jQuery.js).
jQuery UI  responsible for widgets,  components , themes , advanced effects , animation  and interaction mechanism that is UI related things.
Accordions, sliders, dialog boxes, date pickers, and more. All these are ready to be used right now.
jQuery UI  can be used to build highly interactive web applications.
You need to include latest jQuery , UI Core and Flora theme style sheet to work with jQuery UI.
In addition to the above source files you may need to refer each of the component files like ui.draggable.js, ui.resizable.js, ui.accordian.js etc .
or  you may will have to refer jquery.ui.all.js script that contains all component .js files . But do not refer all if you are not using . It is advised to refer only the required files. You can also build the custom download .js file by selecting the required widgets .
This is used for Resizing (resizable method is plugged in jQuery UI), Exploding or animations.
The following is an example code that uses  jQuery UI.
Refer the script files.
1."stylesheet" href="themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)"/>
2.
3.
Refer the required Components
1.
2.
3.
1.$(document).ready(function() {
2.$("#dragme").draggable();
3.$("#dragme-x").draggable({ axis: "x" });
4.$("#accordionDemo").accordion({ event: "mouseover" });
5.$("#dragme-resize").draggable().resizable();
6.})
jQuery UI future is hope to be expecting excited and positive.