You are on page 1of 23

What is MVC?

MVC is a framework methodology that divides an applications implementation into three component roles: models, views, and controllers. Models in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL). Views in a MVC based application are the components responsible for displaying the applications user interface. Typically this UI is created off of the model data (for example: we might create an Product Edit view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object). Controllers in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information it is the controller that handles and responds to user input and interaction. What are the 3 main components of an ASP.NET MVC application? 1. M - Model 2. V - View 3. C - Controller 1- In which assembly is the MVC framework defined? System.Web.Mvc 2- 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. 3- 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. 4- 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. 5- Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms? ASP.NET MVC 6- What is Razor View Engine? Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML. 7- 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. 8- 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. 9- What is namespace of asp.net mvc? ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly. System.Web.Mvc namespace Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders. System.Web.Mvc.Ajax namespace Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings. System.Web.Mvc.Async namespace Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application System.Web.Mvc.Html namespace

Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation. 10- 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. 11- 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. 12- Where are the routing rules defined in an asp.net MVC application? In Application_Start event in Global.asax 13- 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 14- What is the page lifecycle of an ASP.NET MVC? Following process are performed by ASP.Net MVC page: 1) App initialization 2) Routing 3) Instantiate and execute controller 4) Locate and invoke controller action 5) Instantiate and render view 15- 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. 16- 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. 17- How route table is created in ASP.NET MVC? When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table. 18- 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://google.com/search/label/MVC Controller Name = search Action Method Name = label Parameter Id = MVC 19- 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. How do you avoid XSS Vulnerabilities in ASP.NET MVC? Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0. 20- 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.

21- 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. 22- 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. 23- 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. 24- 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. 25- 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} 26- What are the 2 ways of adding constraints to a route? 1. Use regular expressions 2. Use an object that implements IRouteConstraint interface 27- 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. 28- What is the use of action filters in an MVC application? Action Filters allow us to add pre-action and post-action behavior to controller action methods. 29- If I have multiple filters implemented, what is the order in which these filters get executed? 1. Authorization filters 2. Action filters 3. Response filters 4. Exception filters 30- What are the different types of filters, in an asp.net mvc application? 1. Authorization filters 2. Action filters 3. Result filters 4. Exception filters 31- Give an example for Authorization filters in an asp.net mvc application? 1. RequireHttpsAttribute 2. AuthorizeAttribute 32- Which filter executes first in an asp.net mvc application? Authorization filter 33- What are the levels at which filters can be applied in an asp.net mvc application? 1. Action Method 2. Controller 3. Application 34- Is it possible to create a custom filter? Yes

35- What filters are executed in the end? Exception Filters 36- Is it possible to cancel filter execution? Yes 37- What type of filter does OutputCacheAttribute class represents? Result Filter 38- What are the 2 popular asp.net mvc view engines? 1. Razor 2. .aspx 39- What is difference between Viewbag and Viewdata in ASP.NET MVC? The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data. 40- What symbol would you use to denote, the start of a code block in razor views? @ 41- What symbol would you use to denote, the start of a code block in aspx views? <%= %> In razor syntax, what is the escape sequence character for @ symbol? The escape sequence character for @ symbol, is another @ symbol 42- When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks? No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks. 43- When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views? To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml 44- What are sections? Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional. 45- What are the file extensions for razor views? 1. .cshtml - If the programming lanugaue is C# 2. .vbhtml - If the programming lanugaue is VB 46- How do you specify comments using razor syntax? Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. 47- What is Routing? A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. 1. Can you describe ASP.NET MVC Request Life Cycle? Ans. There are two answers for the question. Short Answer: Following are the steps that are executed in ASP.NET MVC Request Life Cycle. I. Receive request, look up Route object in RouteTable collection and create RouteData object. I. Create RequestContext instance. I. Create MvcHandler and pass RequestContext to handler. IV. Identify IControllerFactory from RequestContext. V. Create instance of class that implements ControllerBase. VI. Call MyController.Execute method. V I. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view. Detailed Answer: There are five main steps occurs in ASP.NET Request Life Cycle. I. Initialize Application (Route table is created)

Desc. When we request a page from a normal ASP.NET application, there is a physical copy of page on the disk that is corresponds to each page request. In ASP.NET MVC, there is no page on the disk that corresponds to the request. Request is routed to the controller. The controller is responsible for generating page that is sent back to the browser. ASP.NET MVC has Route Table which stores mapping entries of particular URLs to action methods of contoller. i.e. URL http://jinaldesai.net/Articles/CSharp maps to the CSharp method of Articles controller. In ASP.NET MVC application like normal ASP.NET application when application starts first time, it calls Application_Start() application event from Global.asax. Route table is registered(created) from Appication_Start() event. II. Routing Mechanism (UrlRoutingModule intercepts the request) When a request is coming to ASP.NET MVC application, the request is intercepted by UrlRoutingModule HTTP Module. The first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper2 object. Next, the module passes the wrapped HttpContext to the RouteTable that was setup in the previous step, which includes includes the URL, form parameters, query string parameters, and cookies associated with the current request. Next, the module creates a RouteContext object that represents the current HttpContext and RouteData. The module then instantiates a new HttpHandler based on the RouteTable and passes the RouteContext to the new handlers constructor(In ASP.NET MVC case it is MvcHandler). Last step taken by module is setting MvcHandler as the current HTTP Handler. III. MvcHandler Executes (Instantiate and execute controller) In normal ASP.NET application after second step, it fires set of events including Start, BeginRequest, PostResolveRequestCache, etc. While in case of ASP.NET MVC application, MvcHandler(which is created in previous step) creates appropriate controller instance to serve the request by passing controller name(found through the route mapping table) and RequestContext to the static method CreateController() method of ControllerFactory class(i.e. ControllerFactory.CreateController()) to get particular controller. Next is ControllerContext object is created from the RequestContext and the controller. And the last step in Step 3 is the Execute() method is called on the controller class.(Here factory pattern is implemented) IV. Controller Executes (Locate and invoke controller action) The Controller.Execute() method takes RouteData and other context information to locate appropriate action method. It also maps incoming request parameters(querystring, form, etc) to the parameter list of the controller action method. Next is the controller calls its InvokeAction() method, passing details of the choosen action method and invokes the action method and our code finally runs. V. RenderView Method Invoked (Instantiate and render view) The controller object created in previous step has a property ViewFactory of type IViewFactory. The IViewFactory has a method CreateView(), which is called next by passing view name and other context information. The CreateView() method returns an IView. Next the controller invokes RenderView() method of returned IView with again supplying necessary context information includes ViewData and IHttpResponse object. The response data is a HTML, an image, or any other binary or text data. 2. What is MVP? Ans. MVP(Model View Presentor) is a user interface design pattern engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic. It is derived from MVC(Model View Controller) design pattern. The MVP in the pattern has following description. The model is an interface defining the data to be displayed or otherwise acted upon in the user interface. The view is an interface that displays data (the model) and routes user commands(events) to the presenter to act upon that data. The presenter acts upon the model and the view. It retrieves data from repositories(the model), and formats it for display in the view 3. What is difference between MVC and MVP? Ans. The key difference between MVC and MVP is that MVP truly separates the UI from the domain/service layer of the application. In MVP the presenter assumes the functionality of the middle-man(played by the Controller in MVC). MVP is specially geared towards a page event model such as ASP.NET. For more differences see my article: MVC Vs MVP 4. What is Application Areas in ASP.NET MVC application? Why it is necessary? Ans. An Area in ASP.NET MVC application is subset of the project structure based on a logical grouping. Each area contains area specific models, views and controllers. In ASP.NET MVC we can use the default project structure for most websites without having any problems. However, there are some sites that are very large; keeping all the models, views and controllers in a single folder set can be difficult to manage. For such cases, we can define different project ares in ASP.NET MVC application.

5. What are the different return types controller action method supports in ASP.NET MVC? Ans. There are total nine return types we can use to return results from controller to view. The base type of all these result types is ActionResult. ViewResult (View) : Used to return a webpage from an action method. PartialviewResult (Partialview) : Used to send a section of a view to be rendered inside another view. RedirectResult (Redirect) : Used to redirect to another controller and action method based on a URL. RedirectToRouteResult (RedirectToAction, RedirectToRoute) : Used to redirect to another action method. ContentResult (Content) : Used to return a custom content type as the result of the action method. This is an HTTP content type, such as text/plain. jsonResult (json) : Used to return a message formatted as JSON. javascriptResult (javascript) : Used to return JavaScript code that will be executedin the users browser. FileResult (File) : Used to send binary output as the response. EmptyResult : Used to return nothing (void) as the result. 6. What is action filters in ASP.NET MVC? Ans. In ASP.NET MVC we can run our code before controllers action method is executed or after the action method run. To achieve this we can use action filters. We can apply action filters by applying attributes to action methods. 7. Can you describe different types of action filters in brief? Ans. There are mainly three types of action filters provided in ASP.NET MVC. Authorization Filter : It makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter. Result Filter : It wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter. Execution Filter : It executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter. Apart from the readymade action filters provided by ASP.NET MVC, you can also implement your own action filter by inheriting ActionFilterAttribute abstract class. It has four virtual methods that you can override: OnActionExecuting, OnActionExecuted, OnResultExecuting and OnResultExecuted. To implement an action filter, you must override at least one of these methods. 8. What are the enhancements ASP.NET MVC 3 provided compared to ASP.NET MVC 2? Ans. There are many enhancements come with ASP.NET MVC 3. Following are list of some enhancements in ASP.NET MVC 3. Razor View Engine Partial Page Output Caching Unobtrusive Javascript and Validation New Dynamic ViewModel Property Global Filters New ActionResult Types (HttpNotFoundResult, HttpStatusCodeResult, HttpRedirectResult) Built in JSON binding support 9. What is Data Annotations? Ans. Data Annotations are validation mechanism we can use to validate our data stored in form of Entity Data Model, LINQ to SQL or any other data models. We can use it in form of attributes to our properties of mode class. These attributes provide common validation patterns, such as range checking and required fields. Once we apply these attributes to our model class, ASP.NET MVC will provide both client and server side validation checks with no additional coding required. You can also implement your custom Data Annotation Validator by inheriting ValidationAttribute class and overriding IsValid method. To name a few there is RangeAttribute, RequiredAttribute, StringLengthAttribute, RegularExpressionAttribute, etc. http://msdn.microsoft.com/en- us/library/system.componentmodel.dataannotations.aspx (Complete List of Data Annotation attributes) 10. What are HTML Helpers in ASP.NET MVC? Ans. In MVC, HTML Helpers are much like traditional ASP.NET web form controls. Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state. In most cases, an HTML helper is just a method that returns a string. With MVC, you can create your own helpers, or use the built in HTML helpers. To name a few there is BeginForm(), EndForm(), TextBox(), TextArea(), ListBox(), RadioButton(), etc.

What is Entity Framework?


Entity Framework is an additional layer between application and database that enables the developers to program against the conceptual application model instead of programming directly against the relational storage schema. Will there be any issues adding a table without primary keys to a data model? Every entity must have a key, even in the case where the entity maps to a view. When you use the Entity Designer to create or update a model, the classes that are generated inherit from EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it to the data model.

How do you truncate a table using entity data model? Unfortunately Entity Framework doesnt include anything straight forward to handle this. But we can still call a T-SQL statement using entity framework that will still minimizes the developers work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below. using (var context = new MyTestDbEntities()) { context.ExecuteStoreCommand("TRUNCATE table Dummy"); } How do you query in entity model when the result has a join from from different database other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1 As the entity model doesnt support querying from any entity other than the entities defined in Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the context. Following code snippet shows how to query when other databases are joined. string query = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1"; using (var context = new SampleEntities()) { ObjectResult<DbDataRecord> records = context.ExecuteStoreQuery<DbDataRecord>(query); foreach (DbDataRecord record in records) { //Do whatever you want } } What is minimum requirement for Entity Framework applications to run? The Entity Framework is a component of the .NET Framework so Entity Framework applications can run on any computer on which the .NET Framework starting with version 3.5 SP1 is installed. What is CSDL? Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or WCF Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. More=> http://msdn.microsoft.com/en-us/library/bb399292.aspx What is SSDL? Store schema definition language (SSDL) is an XML-based language that describes the storage model of an Entity Framework application. In an Entity Framework application, storage model metadata is loaded from a .ssdl file (written in SSDL) into an instance of the System.Data.Metadata.Edm.StoreItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses storage model metadata to translate queries against the conceptual model to store-specific commands. What is MSL? Mapping specification language (MSL) is an XML-based language that describes the mapping between the conceptual model and storage model of an Entity Framework application. In an Entity Framework application, mapping metadata is loaded from an .msl file (written in MSL) at build time. The Entity Framework uses mapping metadata at runtime to translate queries against the conceptual model to store-specific commands. More=> http://msdn.microsoft.com/en-us/library/bb399202.aspx What is Entity Data Model? The Entity Data Model (EDM) is a set of concepts that describe the structure of data, regardless of its stored form. The EDM borrows from the Entity-Relationship Model described by Peter Chen in 1976, but it also builds on the Entity-Relationship Model and extends its traditional uses. The EDM addresses the challenges that arise from having data stored in many forms. For example, consider a business that stores data in relational databases, text files, XML files, spreadsheets, and reports. This presents significant challenges in data modeling, application design, and data access. When designing a data-oriented application, the challenge is to write efficient and maintainable code without sacrificing efficient data access, storage, and scalability. When data has a relational structure, data access, storage, and scalability are very efficient, but writing efficient and maintainable code becomes more difficult. When data has an object structure, the trade-offs are reversed: Writing efficient and maintainable code comes at the cost of efficient data access, storage, and scalability. Even if the right balance between these trade-offs can be found, new challenges arise when data is moved from one form to another. The Entity Data Model addresses these challenges by describing the structure of data in terms of entities and relationships that are independent of any storage schema. This makes the stored form of data irrelevant to application design and development. And, because entities and relationships describe the structure of data as it is used in an application (not its stored form), they can evolve as an application evolves. More=> http://msdn.microsoft.com/en-us/library/ee382825.aspx Which are the key concepts of Entity Data Model?

The Entity Data Model (EDM) uses three key concepts to describe the structure of data: entity type, association type, and property. These are the most important concepts in describing the structure of data in any implementation of the EDM. 1. Entity Type: The entity type is the fundamental building block for describing the structure of data with the Entity Data Model. In a conceptual model, entity types are constructed from properties and describe the structure of top-level concepts, such as a customers and orders in a business application. 2. Association Type: An association type (also called an association) is the fundamental building block for describing relationships in the Entity Data Model. In a conceptual model, an association represents a relationship between two entity types (such as Customer and Order). 3. Property: Entity types contain properties that define their structure and characteristics. For example, a Customer entity type may have properties such as CustomerId, Name, and Address. More=> http://msdn.microsoft.com/en-us/library/ee382840.aspx What is .edmx file and what it contains? An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically. How can you tell EF to have a different table or column name than that defined for the class? By convention, EF defines the table and column names based on your class and property names. You can use the [Table] and [Column] annotations to tell EF to use different names. How do you mark a property as required? For example, For a Project, the Name is a required field. You use the [Required] attribute to mark a property as required. What is use of EntityDataSource Control? The ADO.NET EntityDataSource control supports data binding scenarios in Web applications that use the ADO.NET Entity Framework. Like the Entity Framework, the control is available as part of the .NET Framework 3.5, beginning with SP1. Like the other Web server data source controls, the EntityDataSource control manages create, read, update, and delete operations against a data source on behalf of data-bound controls on the same page. The EntityDataSource works with editable grids, forms with user-controlled sorting and filtering, dually bound drop-down list controls, and master-detail pages. more=>http://msdn.microsoft.com/en-us/library/cc488502.aspx What is Model First Approach? A new Model First approach was supported in Visual Studio 2010, which was released together with the second Entity Framework version (Entity Framework v4). In Model First approach the development starts from scratch. At first, the conceptual model is created with Entity Data Model Designer, entities and relations are added to the model, but mapping is not created. After this Generate Database Wizard is used to generate storage (SSDL) and mapping (MSL) parts from the conceptual part of the model and save them to the edmx file. Then the wizard generates DDL script for creating database (tables and foreign keys) If the model was modified, the Generate Database Wizard should be used again to keep the model and the database consistent. In such case, the generated DDL script contains DROP statements for tables, corresponding to old SSDL from the .edmx file, and CREATE statements for tables, corresponding to new SSDL, generated by the wizard from the conceptual part. In Model First approach developer should not edit storage part or customize mapping, because they will be regenerated each time when Generate Database Wizard is launched. What is Code First Approach? Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database. More=>http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx What is Entity SQL? Entity SQL is a SQL-like storage-independent language, designed to query and manipulate rich object graphs of objects based on the Entity Data Model (EDM). More=>http://msdn.microsoft.com/en-us/library/bb399560(v=vs.90).aspx What is LINQ To Entities? LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities. LINQ to Entities enables developers to write queries against the database using one of the supported .NET Framework programming languages such as Visual Basic or Visual C#. More=>http://msdn.microsoft.com/en-us/library/bb386964(v=vs.90).aspx What is EntityClient? System.Data.EntityClient is a storage-independent ADO.NET data provider that contains classes such as EntityConnection, EntityCommand, and EntityDataReader. Works with Entity SQL and connects to storage specific ADO.NET data providers, such as SqlClient. More=>http://msdn.microsoft.com/en-us/library/bb738561(v=vs.90).aspx What is Deferred Loading(Lazy Loading)?

When objects are returned by a query, related objects are not loaded at the same time. Instead they are loaded automatically when the navigation property is accessed. Also known as lazy loading, More=>http://msdn.microsoft.com/en-us/library/dd196179(v=vs.90).aspx What is Eager Loading? The process of loading a specific set of related objects along with the objects that were explicitly requested in the query. More=>http://msdn.microsoft.com/en-us/library/bb896272(v=vs.90).aspx What is Complex Type? A .NET Framework class that represents a complex property as defined in the conceptual model. Complex types enable scalar properties to be organized within entities. Complex objects are instances of complex types. More=>http://msdn.microsoft.com/en-us/library/bb738472(v=vs.90).aspx What is Conceptual Model? An implementation of the Entity Data Model (EDM), specific to the Entity Framework, which represents an abstract specification for the data structures that define an entity-relationship representation of data in the domain of an application. More=>http://msdn.microsoft.com/en-us/library/bb399183(v=vs.90).aspx What is use of Entity Container? Specifies entity sets and association sets that will be implemented in a specified namespace. More=>http://msdn.microsoft.com/en-us/library/bb399557(v=vs.90).aspx What is Explicit Loading? When objects are returned by a query, related objects are not loaded at the same time. By default, they are not loaded until explicitly requested using the Load method on a navigation property. More=>http://msdn.microsoft.com/en-us/library/dd196179(v=vs.90).aspx What do you mean by Navigation Property? A property of an entity type that represents a relationship to another entity type, as defined by an association. Navigation properties are used to return related objects as an EntityCollection or an EntityReference, depending on the multiplicity at the other end of the association. More=>http://msdn.microsoft.com/en-us/library/bb399562(v=vs.90).aspx What is scalar property? A property of an entity that maps to a single field in the storage model. What is split entity? An entity type that is mapped to two separate types in the storage model. What do you mean by table-per-hierarchy? A method of modeling a type hierarchy in a database that includes the attributes of all the types in the hierarchy in one table. More=>http://msdn.microsoft.com/en-us/library/bb738443(v=vs.90).aspx What do you mean by table-per-type? A method of modeling a type hierarchy in a database that uses multiple tables with one-to-one relationships to model the various types. More=>http://msdn.microsoft.com/en-us/library/bb738685(v=vs.90).aspx

1).What is Jquery?
jquery is javascript library which required a jquery.js file. After that you can write the jquery as fallows. It uses "$" as the short hand to write jquery code. Simple Syntax is Code: $(document).ready(function() { function body }); 2).When Jquery founded and by whome? It was released in January 2006 at BarCamp NYC by John Resig(Jquery founder). 3).What scripting language is jQuery written in? Ans: JavaScript 4).Write a basic code for add jquery library to pages?

Code: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // You can write the code here </script> </head> <body> <a href="http://www.tutoriz.com/">Jquery Interview Questions and Answers</a> </body> </html> 5).What is jQuery Selectors? Give some examples. Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element. Code: Selector Example Selects * $("*") All elements #id $("#lastname") The element with id=lastname .class $(".intro") All elements with class="intro" element $("p") All p elements For more click here http://www.w3schools.com/jquery/jquery_r...ectors.asp 6).What $("div.tutoriz") will select? Ans: All the div element with tutoriz class. 7).jQuery uses CSS selectors and XPath expressions to select elements true or false? Ans:- True 8).What are the fastest selectors in Jquery? Ans: ID and element selectors are the fastest selectors 9).What are the slower selecoters in Jquery? Ans: Class selectors are slower 10).Which one is faster Jquery ID selector or JavaScript getElementById()? (Jquery ID selector vs JavaScript getElementById()) Ans: JavaScript getElementById() is faster than Jquery Id ($("#elementID")) selector 11).Where Jquery code execute? On client browser or server browser? On client browser 12).Write the code for selecting the 1st div element, 4th div element last div, and for even and odd div elemets also. one by one? apply the red color on the above div. Code: <div class="questions"> <div class="box"> Question</div> <div class="box"> Question</div> <div class="box"> Question</div> <div class="box"> Question</div> <div class="box"> Question</div> <div class="box"> Question</div> </div> Code for first div : $("div.questions > div:first").css("color", "red"); Code for 4th div : $("div.questions > div:nth-child(4)").css("color", "red"); Code for last div : $("div.questions > div:last").css("color", "red"); Code for even div : $("div.questions > div:even").css("color", "red"); Code for odd div : $("div.questions > div:odd").css("color", "red");

13).Write the code for select second last div element? Code for second last div : $("div.questions > div::nth-last-child(2)").css("color", "red"); <!-- Introduced in CSS3 --> 14).What are the advantages of using jQuery over JavaScript in ASP.NET web application Ans: Below are the advatages of using jQery over JavaScript a>.Jquery is well written optimised javascript code so it will be faster in execution unless we write same standard optimised javascript code. b>.Jquery is concise java script code ,means minimal ammount of code is to be written for the same functionality than the javascript. c>.Javascript related Development is fast using Jquery because most of the functionality is already written in the library and we just need to use that. d>.Jquery has cross browser support ,so we save time for supporting all the browsers. 15).What is Chaining in jQuery? Ans: In jQuery, Chaining means to connect multiple functions, events on selectors. look at Sample Code 1 and 2. Code: Sample Code 1 ?$(document).ready(function(){ $('#dvContent').addClass('dummy'); $('#dvContent').css('color', 'red'); $('#dvContent').fadeIn('slow'); });? Sample Code 2 (using Chaining) ?$(document).ready(function(){ $('#dvContent').addClass('dummy') .css('color', 'red') .fadeIn('slow'); });? Both the sample codes above will perform the exact same thing but the only difference is that Sample code 2 is using Chaining. But Code 2 is faster and shorter then Code 1. The problem with the Sample Code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one. This is the advantage of Chaining. For read more click on the below link http://jquerybyexample.blogspot.com/2012...query.html http://tobiasahlin.com/blog/quick-guide-...in-jquery/ 16).Is jQuery a library for client scripting or server scripting? Ans: Client Script 17).What is jQuery & its significance? Why it is so popular?... 18).What are features of JQuery or What can be done using JQuery? Features of Jquery 1. One can easily provide effects and can do animations. 2. Applying / Changing CSS. 3. Cool plugins. 4. Ajax support 5. DOM selection events 6. Event Handling 19).How to check Jquery UI loaded or not? Ans: // Checking if jQuery UI is loaded or not Code: if($.ui){ // jQuery UI is loaded }else {

// jQuery UI is not loaded } 20).How check currently loaded jQuery UI version on the page? Ans: // Returns jQuery UI version (ex: 1.8.2) or undefined $.ui.version 21).Write the code for setting datetimepicker on textbox click. If below is our textbox <input type="text" id="abc" name=%26quot%3Bacc%26quot%3B value="Select Date" /> then Jquery code will be $("#abc").datepicker();

22).If you have a table, how you will apply the two differt color on alternate rows using Jquery? Code: <table border="1"> <tr><td>Vikas Ahlawat</td></tr> <tr><td>Edwin George</td></tr> <tr><td>Rohit Khurana</td></tr> <tr><td>Gyan Singh</td></tr> </table> Ans : <script src="jquery.js"></script> <script> $(document).ready(function() { $("tr:even").css("background-color", "#f4f4f8"); $("tr:odd").css("background-color", "#ffffff"); }); </script> 23).Name the Jquery method which is used to hide selected elements? Ans: .hide() 24).Name the Jquery methods which are used for apply css class? Ans: $("#Id1").addClass('YourClassName'); // for apply class $("#Id1").removeClass('YourClassName'); // for remove class 25).What is the use of attr() method in Jquery? The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the first matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements. Code: $(selector).attr(attribute) //it will return the value of an attribute $(selector).attr(attribute,value) //it will set the value of an attribute $(selector).attr({attribute:value, attribute:value,...}) //for set multiple attribute 26).Can we use both jQuery and AJAX together? Ans: yes 27).Tell the name of jQuery method which is used to perform an asynchronous HTTP request? Ans: jQuery.ajax() 28).What is the use of jquery load() method? The jQuery load() method is a powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element without reload the complate page. Ex:The following example loads the content of the file "demo_test.txt" into a specific <div> element $("#div1").load("demo_test.txt"); 29).Can we use our own specific charactor in the place of $ sigh in Jquery?

Ans: Yes You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Here is an example: Code: var vikas = $.noConflict(); vikas(document).ready(function(){ vikas("button").click(function(){ vikas("p").text("jQuery is still working!"); }); }); 30).Name the 5 Jquery events? Ans:jQuery Events jQuery click() event. jQuery dblclick() event. jQuery mouseenter() event. jQuery mouseleave() event. jQuery mousedown() event. jQuery mouseup() event. jQuery hover() event. jQuery focus() and blur() events.

1. What is Language Integrated Query (LINQ)?


LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language. 2. What are LINQ query expressions? A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source. 3. Write the basic steps to execute a LINQ query. The following are the three basic steps to execute a LINQ query: Obtain the data source (The data source can be either an SQL database or an XML file) Create a query Execute the query 4. Write the basic syntax of a LINQ query in Visual Basic as well as in C#. In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order. In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order. 5. In which statement the LINQ query is executed? A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#. 6. In LINQ, lambda expressions underlie many of the standard query operators. Is it True or False? It is true. 7. What is PLINQ? PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in which a query can be executed by using multiple processors. PLINQ ensures the scalability of software on parallel processors in the execution environment. It is used where data grows rapidly, such as in telecom industry or where data is heterogeneous. PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel execution provides a major performance improvement to PLINQ over certain types of legacy code, which takes too much time to execute. 8. What are the different Visual Basic features that support LINQ?

Visual Basic includes the following features that support LINQ: Anonymous types - Enables you to create a new type based on a query result. Implicitly typed variables - Enables the compiler to infer and assign a type when you declare and initialize a variable. Extension method - Enables you to extend an existing type with your own methods without modifying the type itself. 9. What is the function of the DISTINCT clause in a LINQ query? The DISTINCT clause returns the result set without the duplicate values. 10. What is the DataContext class and how is it related to LINQ? After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface. 11. What is the difference between the Take and Skip clauses? The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string. 12. What is Object Relational Designer (0/R Designer)? The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database. 13. Which interface implements the standard query operators in LINQ? The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface in C# and the IEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic. 14. What are standard query operators in LINQ? The standard query operators in LINQ are the extension methods that form the LINQ pattern. These operators form an API that enables querying of any .NET array or collection. It operates on sequences and allows you to perform operations, such as determining if a value exists in the sequence and performing an aggregated function, such as a summation over a sequence. 15. On what parameter does the GroupBy clause group the data? The GroupBy clause groups the elements that share a common attribute. 16. What is a LinqDataSource control? The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource and ObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, the LinqDataSource control is designed to bind a LINQ enabled data model. 17. How can you open the O/R Designer? You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project. 18. The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable<T> interface in Visual Basic. Is it True or False? False, as it implements the IEnumerable(T) interface in Visual Basic and the IEnumerable<T> interface is implemented in C#. 19. What are lambda expressions in LINQ? A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. 20. Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this? You can load the data into the dataset by using different methods, such as: Using the DataAdapter class Using LINQ to SQL 21. What are the different implementations of LINQ? The different implementations of LINQ are: LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects. LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.

LINQ to XML - Provides an in-memory XML programming interface. LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML. 22. Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework? The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component. 23. Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture. The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture. 24. What is the difference between the Select clause and SelectMany() method in LINQ? Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query. 25. Which extension method do you need to run a parallel query in PLINQ? The AsParallel extension method is required to run a parallel query in PLINQ. WCF Interview Questions What is WCF? WCF stands for Windows Communication Foundation (WCF) and is considered as the Microsoft Service-Oriented Architecture (SOA) platform for building distributed and interoperable applications. WCF unifies ASMX, Remoting, and Enterprise Services stacks and provides a single programming model. WCF services are interoperable and supports all the core Web services standards. WCF services also provide extension points to quickly adapt to new protocols and updates and integrates very easily with the earlier microsoft technologies like Enterprise Services, COM and MSMQ. What is the version of the .NET framework in which WCF is released? WCF - Windows Communication Foundation is released as part of .NET Framework 3.0. WPF (Windows Presentation Foundation), WF (Workflow Foundation) and Card Space are also part of .NET Framework 3.0. What is the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc.? To understand the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc, let's consider the following scenario. We have developed an application using web services. As we know web services use HTTP protocl and XML SOAP formatted messages, they are good for developing interoperable applications in a heterogeniuos environment. We have a new client. Our new client is using .NET and he wants binary formmatted messages over TCP protocol, because interoperability is not a concern and binary formmatted messages over TCP protocol are much faster than XML SOAP formmatted messages over HTTP. To satisfy the requirement of this client, now we cannot use our existing web service. So, we have to develop a brand new remoting application from the scratch. The business functionality is the same in web services and remoting application. Since our different clients have different requirements, we ended up creating the same business application using web services and remoting technologies. This approach has several disadvantages as listed below. 1. Developers have to be familiar with two different technologies (Web Services and Remoting). 2. We end up creating duplicate business applications with different technologies which also leads to maintainance overhead. On the other hand WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof. For the same requirement that we have seen untill now, we just create one application and expose multiple end points to satisfy the requirements of multiple clients. In WCF configuration drives protocol choices, messaging formats, process allocation, etc. WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, or hosting environment. Everything is configurable. Why are WCF Services are considered as loosely coupled? WCF Services are considered as loosely coupled because WCF services are not tightly bound to a particular protocol, encoding format, or hosting environment. All of these are configurable. At the time of designing WCF services, we donot have to worry about what protocol, encoding format, or hosting environment to use to expose the service. We can worry about all these at the time of deployment. What are the 3 things that a WCF Services end point must have? / What are the ABC of a WCF service? Address - The address where the WCF Service is hosted. Binding - The binding that decides the protocol, message encoding and security to use. Binding also decides whether to use reliable messaging and transaction support. Contract - The service contract defines what service operations are available to the client for consumption. So the Address(A), Binding(B) and Contract(C) are called as the ABC of the service end point. What is the role of WSDL in WCF?/What is WSDL? WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the clients, to generate proxies and the configuration file. The WSDL file provides the following information for the consumers of the WCF service.

1. Provides the information about the service contract and operations available. 2. Provides the information about all the end points exposed by the WCF service. 3. Provides the information about the messages and types that can be exchanged between the client and the WCF service. 4. WSDL also provides any information about the policies used. What is the tool that a client application can use to generate the proxy for a WCF service? Service Utility (svcutil.exe) can be used by the clients to generate the proxy and configuration file. For the client to be able to generate proxies, the service should enable metadata exchange. Define Service Contracts and Operation Contracts in WCF? 1. Service Contract - An interface that exposes the service operations is usually decorated with the service contract attribute. Always provide meaningful Namespace and Name to a service contract as shown in theexample below.

2. Operation Contract - All methods in a service contract should have OperationContract attribute. You can also provide explicit Name, Action and ReplyAction as shown in the example below.

Can you apply, ServiceContract attribute to a class rather than an interface in WCF? Yes, a ServiceContract attribute can be applied either to a class or an interface, but defining service contracts using interfaces rather classes has the following benifits. 1. Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation can be changed at will without affecting the clients. 2. Defining service contracts using interfaces, also allows a service to implement more than 1 contract. What is the purpose of MessageParameter attribute in WCF? MessageParameter attribute is used to control the parameter and returned object names from a service operation. Consider the example below. On the service side, the method parameter name in SaveCustomer([MessageParameter(Name = "Customer")] Customer cust) is cust. If we donot use MessageParameter attribute, then "cust" is what is exposed as parameter name to the client, which is not very proffesional. So we are using MessageParameter attribute to expose the method parameter name as Cutomer.

What are the different options available to serialize complex types that are sent and received between clients and services in WCF? The following are the different options available to serialize complex types that are exchanged between clients and services in WCF. These options have their own advantages and disadvanatages. Data contracts is thepreferred way to serialize complex types in WCF. 1. Serializable types - Us the Serializable attribute on the type that you want to serialize 2. Data contracts - Use DataContract attribute on the type and DataMember attribute on every member of the type, that you want to serialize. You can apply DataMember attribute either on a filed or a property. 3. Known types - Use Known types to enable polymorphic behavior in service contracts. 4. IXmlSerializable - IXmlSerializable types provide XSD schema to Web Services Description Language(WSDL) and metadata exchange (MEX). What is the disadvantage of using Serializable attribute to serialize a complex type that is sent and received between clients and services in WCF? When we decorate a class with Serializable attribute, all the fields of the class are serialized regardless of the accessibility. We donot have

control on what to serialize and what not to serialize. We also will not have any control over naming conventions or data types. What is the preferred way for serializing complex types in WCF? The preferred way for serializing complex types in WCF is to use data contracts. Using Data Contracts provides us with the following advantages. 1. Using DataMember attribute, you can control which members of the class to serialize. 2. You can also control the order in which members are serialized using Order parameter of the DataMember attribute.. 3. You can also provide explicit Name to the serialized members using Name parameter of the DataMember attribute. 4. You can also specify if a member is required or optional using IsRequired parameter of the DataMember attribute. Consider the example below which uses Name, IsRequired and Order parameters of the DataMember attribute to serialize CustomerId property. By the way DataMember attribute can be used with either fields or properties. If you donot specify the order in which members are serialized, then by default alphabetical ordering is done by the DataContractSerializer. What is the best way to serialize Polymorphic Types in WCF? The best way to serialize Polymorphic Types in WCF is to use KnownType attribute on the parent type as shown in the example below. CorporateCustomer and PremiumCustomer classes inherit from Customer class,and hence we can associate CorporateCustomer and PremiumCustomer types as known types in 3 different ways depending on the project requirement. 1. Associate known types to the base types themselves. 2. Associate known types to particular operations. 3. Associate known types to the service contract as a whole. In Example 1, we are associating known types, CorporateCustomer and PremiumCustomer to the base type, Customer.

In Example 2, we are associating known type, CorporateCustomer on SaveCorporateCustomer(Customer customer) and GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute.

In Example 3, we are associating known types, CorporateCustomer and PremiumCustomer to the service contract ICustomerService as a whole.

It is also possible to specify known types in a configuration file rather than in code. Example 4 shows how to specify known types in configuration.file.

Explain the significane of MessageContract attribute?/Why and When do you use MessageContract attribute? There are several advantages of using MessageContract attribute in WCF. MessageContract attribute can be used for 1. Adding custom headers to the message. 2. Controling message wrapping. 3. Controling signing and encryption of messages. MessageContract attribute provides us with greater control over message headers and body elements. MessageContract attribute converts a type to a SOAP message. The example below shows how to use IsWrapped and ProtectionLevel parameters of MessageContract attribute. You may also set an explicit Name and Namespace.

MessageContract attribute is supported by MessageHeader attribute and MessageBodyMember attribute. You can apply MessageHeader attribute to fields or properties of message contract. This is a simple technique for creating custom headers.You can provide Name, Namespace and ProtectionLevel. You may also set SOAP protocol settings like Relay, Actor, MustUnderstand.

MessageBodyMember attribute can also be Applied to fields or properties of message contract.Can have several body elements. This is equivalent to multiple parameters in operation and this is the only way to return multiple complex types. It is suggested as a good practice to always supply Order. You can also set Name, Namespace, ProtectionLevel. The example below shows how to use MessageHeader and MessageBodyMember attributes.

What is WS-Policy?/What is Web Services Policy? Web Services Policy or WS-Policy is an interoperable standard for describing policies that influence communication with the clients. Usually WS-Policy is included in the WSDL contract exposed by the WCF service, although it is optional. What is the use of WS-Policy? WS-Policy is generally used for 1. Describing protocols for accessing operations 2. Security 3. Reliable messaging 4. Transactions 5. Message encoding (Message Transmission Optimization Mechanism [MTOM]) 6. Other protocols You can specify the above settings in WSDL directly without a policy section, but the disadvantage is that, once published, the WSDL contract is final. If the clients has to communicate with a WCF service that has changed the settings in the WSDL, the clients need to rebuild the proxy and configuration or atleast the changes to the WSDL contract must support backward compatibility. The advantage of using WS-Policy is that it can change over time, and the clients can discover the changed policy to communicate via metadata exchange. But keep in mind that, you can only change the policy safely if clients are positioned to handle dynamic changes Are WCF Contracts version tolerant? Yes, WCF contracts are version tolerant by default. Service contracts, data contracts, and message contracts forgive missing and non required data. They also Ignore any superfluous or additional data sent by the client to the service. The DataContractSerializer provides tolerance. Reasonable changes can be made without impacting existing clients. The following table summarizes the changes to a service contract and impact on existing clients.

What is IExtensibleDataObject? OR What is the advantage and disadvantage of implementing IExtensibleDataObject? WCF guidelines recommend enhancing all data contracts with support of IExtensibleDataObject interface, to preserve unexpected data from clients. During deserialization, superfluous data is placed in a dictionary on the service side and during serialization, the same data is written as XML as it was originally provided by the client. This is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also useful in case where downstream calls from version 2.0 services go to other services handling version 1.0. However, there is also a disadvantage of implementing IExtensibleDataObject. It carries risks of denial of service (DoS) and unnecessary use of server resources. We can turn on and off, the support for IExtensibleDataObject either in code declaratively using attributes or in the configuration file as shown below.

Disabling support for IExtensibleDataObject in Code using attributes

Disabling support for IExtensibleDataObject in configuration What are SOAP Faults in WCF? Common language runtime (CLR) exceptions do not flow across service boundaries. At the maximum, a CLR exceptions may propagate up to the service tier from business components. Unhandled CLR exceptions reach the service channel and are serialized as SOAP faults before reporting to clients. An unhandled CLR exception will fault the service channel, taking any existing sessions with it. That is why it is very importatnt to convert the CLR exceptions into SOAP faults. Where possible, throw fault exceptions SOAP faults are standards based and interoperable. There are 2 formats used by SOAP faults, SOAP 1.1 and SOAP 1.2. SOAP format depends on the binding used. What happens if there is an unhandled exception in WCF? If there is an unhandled exception in WCF, the the service model returns a general SOAP fault, that does not include any exception specific details by default. However, you can include exception details in SOAP faults, using IncludeExceptionDetailsInFaults attribute. If IncludeExceptionDetailsInFaults is enabled, exception details including stack trace are included in the generated SOAP fault. IncludeExceptionDetailsInFaults should be enabled for debugging purposes only. Sending stack trace details is risky. What are the 2 ways to enable IncludeExceptionDetailsInFaults for a WCF service? Either programatically or thru configuration. To enable thru code use ServiceBehaviorAttribute as shown below: [ServiceBehaviourAttribute(IncludeExceptionDetailsInFaults=true)] public class PragimService : IPragimService To enable using configuration use servicedebug element as shown below

What are bindings in WCF? Bindings in WCF define the configuration of communication channel between clients and services. Binding specifies 1. Transport Protocol 2. Message encoding 3. Security Mechanism 4. Reliable Messaging 5. Transactions Support What are different Transport protocols available in WCF?

1. TCP 2. HTTP 3. Named Pipes 4. MSMQ What message encoding formats are available in WCF? 1. Text - For interoperability 2. MTOM (Transmission Optimization Mechanism) - For transfering large objects 3. Binary - For speed What are the 2 ways available for configuring bindings in WCF? 1. Declaratively using a configuration file 2. Programatically in the code. Using configuration file has several advantages. List a few standard bindings available in WCF? 1. BasicHttpBinding 2. NetPeerTcpBinding 3. WSFederationHttpBinding 4. NetNamedPipeBinding 5. WSHttpBinding 6. WSDualHttpBinding 7. NetTcpBinding 8. NetMsmqBinding 9. MsmqIntegrationBinding Can you create a customized binding in WCF? Yes, bindings in WCF are completely extensible and we can create a customized one. Can you overload methods in a WCF service? Yes, it is possible to overload methods in a WCF service, but the names of the exposed operation contracts must be unique. To achieve this we can use the Name property of OperationContractAttribute. Let us understand this with an example. If I have the WCF service designed as shown below, the service compiles without any issues. When we try to run the service, we will get InvalidOperationException.

What are the different message exchanging patterns available in WCF? There are 3 main different message exchanging patterns available in WCF. 1. Request-Reply - In the request-reply pattern, a client application sends a message to a WCF service and then waits for a reply. This is the classic and most commonly used message exchange pattern in WCF. 2. One-Way - In a one way message exchange pattern no response is sent back, even if there is an exception. In the one-way message exchange pattern, a client application sends a message to a WCF service but the service does not send a reply message to the client. You can use this

pattern when a client requests the service take an action but does not need to wait for a reply. 3. Duplex - In the request/reply and one-way message exchange patterns, only the client can initiate communication. In the duplex pattern, both the client and the service can initiate communication. The client calls a method of the service. The service can then use a client callback to call a method in the client. You can use this pattern when you want the service to send a notification or alert to the client after the client has called the service. What is the default message exchange pattern used in WCF? Request/Reply How do you setup a one way operation? Set OperationContractAttribute's IsOneWay property to true. An example is shown below.

What is MTOM? MTOM stands for Message Transmission Optimization Mechanism and is an Interoperable standard that reduces the overhead of large binary data transfera. Removes bloat and processing overhead of base64 encoded data. Improves overall message transfer performance. To correct this we can use the Name property of OperationContractAttribute as shown below. After this change, the service works fine both at compile and runtime.

You might also like