Friday, 9 September 2016

MVC Part 2

1) Explain what is Model-View-Controller?
MVC is a software architecture pattern for developing web application. It is handled by three objects Model-View-Controller.
2) Mention what does Model-View-Controller represent in an MVC application?
In an MVC model,
  • Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data
  • View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the VIEW
  • Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface.  The user input logic is contained with-in the controller
3) Explain in which assembly is the MVC framework is defined?
The MVC framework is defined in System.Web.Mvc.
4) List out few different return types of a controller action method?
  • View Result
  • Javascript Result
  • Redirect Result
  • Json Result
  • Content Result
5) Mention what is the difference between adding routes, to a webform application and an MVC application?
To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection class, where adding routes to an MVC application, you can use MapRoute() method.
mvc-design-diagram
6) Mention what are the two ways to add constraints to a route?
The two methods to add constraints to a route is
  • Use regular expressions
  • Use an object that implements IRouteConstraint Interface
7) Mention what is the advantages of MVC?
  • MVC segregates your project into a different segment, and it becomes easy for developers to work on
  • It is easy to edit or change some part of your project that makes project less development and maintenance cost
  • MVC makes your project more systematic
8) Mention what “beforFilter()”,“beforeRender” and “afterFilter” functions do in Controller?
  • beforeFilter(): This function is run before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
  • beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used, but may be required If you are calling render() manually before the end of a given action
  • afterFilter(): This function is called after every controller action, and after rendering is done. It is the last controller method to run
9) Explain the role of components Presentation, Abstraction and Control in MVC?
  • Presentation: It is the visual representation of a specific abstraction within the application
  • Abstraction: It is the business domain functionality within the application
  • Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system
10) Mention the advantages and disadvantages of MVC model?
AdvantagesDisadvantages
  • It represents clear separation between business logic and presentation logic
  • Each MVC object has different responsibilities
  • The development progresses in parallel
  • Easy to manage and maintain
  • All classes and object are independent of each other
  • The model pattern is little complex
  • Inefficiency of data access in view
  • With modern user interface, it is difficult to use MVC
  • You need multiple programmers for parallel development
  • Multiple technologies knowledge is required
11) Explain the role of “ActionFilters” in MVC?
In MVC “ ActionFilters” help you to execute logic while MVC action is executed or its executing.
12) Explain what are the steps for the execution of an MVC project?
The steps for the execution of an MVC project includes
  • Receive first request for the application
  • Performs routing
  • Creates MVC request handler
  • Create Controller
  • Execute Controller
  • Invoke action
  • Execute Result
13) Explain what is routing? What are the three segments for routing is important?
Routing helps you to decide a URL structure and map the URL with the Controller.
The three segments that are important for routing is
  • ControllerName
  • ActionMethodName
  • Parameter
14) Explain how routing is done in MVC pattern?
There is a group of routes called the RouteCollection, which consists of registered routes in the application.  The RegisterRoutes method records the routes in this collection.  A route defines a URL pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches.  The third parameter might be the default values for the placeholders if they are not determined.
15) Explain using hyperlink how you can navigate from one view to other view?
By using “ActionLink” method as shown in the below code. The below code will make a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.
Collapse / Copy Code
<%= Html.ActionLink(“Home”, “Gotohome”) %>
16) Mention how can maintain session in MVC?
Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.
17) Mention what is the difference between Temp data, View, and View Bag?
  • Temp data: It helps to maintain data when you shift from one controller to other controller.
  • View data: It helps to maintain data when you move from controller to view
  • View Bag: It’s a dynamic wrapper around view data
18) What is partial view in MVC?
Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In simple terms, partial view allows to render a view within the parent view.
19) Explain how you can implement Ajax in MVC?
In Ajax, MVC can be implemented in two ways
  • Ajax libraries
  • Jquery
20) Mention what is the difference between “ActionResult” and “ViewResult” ?
“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.  “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult” .
“ActionResult” is best if you are deriving different types of view dynamically.
21) Explain how you can send the result back in JSON format in MVC?
In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.
22) Explain what is the difference between View and Partial View?

                            View                               Partial View
  • It contains the layout page
  • Before any view is rendered, viewstart page is rendered
  • View might have markup tags like body, html, head, title, meta etc.
  • View is not lightweight as compare to Partial View
  •  It does not contain the layout page
  • Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
  • Partial view is designed specially to render within the view and just because of that it does not consist any mark up
  • We can pass a regular view to the RenderPartial method
23) List out the types of result in MVC?
In MVC, there are twelve types of results in MVC where “ActionResult” class is the main class while the 11 are their sub-types
  • ViewResult
  • PartialViewResult
  • EmptyResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • JavaScriptResult
  • ContentResult
  • FileContentResult
  • FileStreamResult
  • FilePathResult
24) Mention what is the importance of NonActionAttribute?
All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.
25) Mention what is the use of the default route {resource}.axd/{*pathinfo} ?
This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.
26) Mention the order of the filters that get executed, if the multiple filters are implemented?
The filter order would be like
  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters
27) Mention what filters are executed in the end?
In the end “Exception Filters” are executed.
28) Mention what are the file extensions for razor views?
For razor views the file extensions are
  • .cshtml: If C# is the programming language
  • .vbhtml: If VB is the programming language
29) Mention what are the two ways for adding constraints to a route?
Two methods for adding constraints to route is
  • Using regular expressions
  • Using an object that implements IRouteConstraint interface
30) Mention two instances where routing is not implemented or required?
Two instance where routing is not required are
  • When a physical file is found that matches the URL pattern
  • When routing is disabled for a URL pattern
31) Mention what are main benefits of using MVC?
There are two key benefits of using MVC
  • As the code is moved behind a separate class file, you can use the code to a great extent
  • As behind code is simply moved to.NET class, it is possible to automate UI testing. This gives an opportunity to automate manual testing and write unit tests.

MVC Part 1



Question 1: What does MVC stand for>


Answer: Model-View-Controller.

Question 2: What are three main components or aspects of MVC?

Answer: Model-View-Controller

Question 3: Which namespace is used for ASP.NET MVC? Or which assembly is used to define the MVC framework?
Answer: System.Web.Mvc

Question 4: What is the default view engine in ASP.NET MVC?
Answer: Web Form(ASPX) and Razor View Engine.

Question 5: Can we remove the default View Engine?
Answer: Yes, by using the following code:
  1. protected void Application_Start()  
  2. {  
  3.       ViewEngines.Engines.Clear();  
  4. }  
Question 6: Can we have a Custom View Engine?
Answer: Yes, by implementing the IViewEngine interface or by inheriting from the VirtualPathProviderViewEngine abstract class.

Question 7: Can we use a third-party View Engine?
Answer: Yes, ASP.NET MVC can have Spark, NHaml, NDjango, Hasic, Brail, Bellevue, Sharp Tiles, String Template, Wing Beats, SharpDOM and so on third-party View Engine.

Question 8: What are View Engines?
Answer: View Engines are responsible for rendering the HTML from your views to the browser.

Question 9: What is Razor Engine?
Answer: The Razor view engine is an advanced view engine from Microsoft, packaged with MVC 3. Razor uses an @ character instead of aspx's <% %> and Razor does not require you to explicitly close the code-block.

Question 10: What is scaffolding?
Answer: Quickly generating a basic outline of your software that you can then edit and customize.

Question 11: What is the name of Nuget scaffolding package for ASP.NET MVC3 scaffolding?
Answer: MvcScaffolding

Question 12: Can we share a view across multiple controllers?
Answer: Yes, it is possible to share a view across multiple controllers by putting a view into the shared folder.

Question 13: What is unit testing?
Answer: The testing of every smallest testable block of code in an automated manner. Automation makes things more accurate, faster and reusable.

Question 14: Is unit testing of MVC application possible without running the controller?
Answer: Yes, by the preceding definition.

Question 15: Can you change the action method name?
Answer: Yes, we can change the action method name using the ActionName attribute. Now the action method will be called by the name defined by the ActionName attribute.
  1. [ActionName("DoAction")]  
  2. public ActionResult DoSomething()  
  3. {  
  4.       /TODO:  
  5.       return View();  
  6. }   
Question 16: How to prevent a controller method from being accessed by an URL?
Answer: By making the method private or protected but sometimes we need to keep this method public. This is where the NonAction attribute is relevant.

Question 17: What are the features of MVC5?
Answer:
  • Scaffolding
  • ASP.NET Identity
  • One ASP.NET
  • Bootstrap
  • Attribute Routing
  • Filter Overrides
Question 18: What are the various types of filters in an ASP.NET MVC application?
Answer:
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
Question 19: If there is no match in the route table for the incoming request's URL, which error will result?
Answer: 404 HTTP status code

Question 20: How to enable Attribute Routing?
Answer: By adding a Routes.MapMvcAttributeRoutes() method to the RegisterRoutes() method of the RouteConfig.cs file.

Advantages of WCF Over Web service

Web Service in ASP.NET

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

WCF Service

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • Service Orientation
  • Interoperability
  • Multiple Message Patterns
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • AJAX and REST Support
  • Extensibility

Difference between Web Service in ASP.NET & WCF Service

WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializerwhich is better in Performance as compared to XmlSerializer.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized

Important difference between DataContractSerializer and XMLSerializer

  • A practical benefit of the design of the DataContractSerializer is better performance overXmlserializer.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereasDataCotractSerializer
  • Explicitly shows the which fields or properties are serialized into XML
  • The DataContractSerializer can translate the HashTable into XML

Sunday, 4 September 2016

Inner Join Example in LINQ

Let see an example of using the Join method in LINQ and C#. The Join method performs an inner equijoin on two sequences, correlating the elements of these sequences based on matching keys. It is called equijoin, since we are testing for equality using the equals operator.
If you are familiar with relational databases, then in an inner join, each element of the first collection appears one time for every matching element in the second collection. If an element in the first collection has no matching elements, it does not appear in the join result set. The Join method in LINQ does the same.
We will using two classes Book and Order and use the Join operator on them and see the results. Here’s some sample data:
class Program{
    static void Main(string[] args)
    {
        List<Book> bookList = new List<Book>
        {
            new Book{BookID=1, BookNm="DevCurry.com Developer Tips"},
            new Book{BookID=2, BookNm=".NET and COM for Newbies"},
            new Book{BookID=3, BookNm="51 jQuery ASP.NET Recipes"},
            new Book{BookID=4, BookNm="Motivational Gurus"},
            new Book{BookID=5, BookNm="Spiritual Gurus"}
        };

        List<Order> bookOrders = new List<Order>{
            new Order{OrderID=1, BookID=1, PaymentMode="Cheque"},
            new Order{OrderID=2, BookID=5, PaymentMode="Credit"},
            new Order{OrderID=3, BookID=1, PaymentMode="Cash"},
            new Order{OrderID=4, BookID=3, PaymentMode="Cheque"},
            new Order{OrderID=5, BookID=3, PaymentMode="Cheque"},
            new Order{OrderID=6, BookID=4, PaymentMode="Cash"}
        };
    }
}

public class Book{
    public int BookID { get; set; }
    public string BookNm { get; set; }
}

public class Order{
    public int OrderID { get; set; }
    public int BookID { get; set; }
    public string PaymentMode { get; set; }
}
Let us apply a Join between Book and Order collection
var orderForBooks = from bk in bookList
            join ordr in bookOrders
            on bk.BookID equals ordr.BookID
            select new
            {
                bk.BookID,
                Name = bk.BookNm,
                ordr.PaymentMode
            };

foreach (var item in orderForBooks)
    Console.WriteLine(item);

Console.ReadLine();
In the code shown above, the query uses the join clause to match Book objects with Order objects testing it for equality using the equals operator.The select clause defines how the result will appear using anonymous types that consist of the BookID, Book Name and Order Payment Mode.

LINQ has a JOIN query operator that provides SQL JOIN like behavior and syntax. As you know, Inner join returns only those records or rows that match or exists in both the tables. The simple inner join example is given below:
  1. DataContext context = new DataContext();
  2. var q = (from pd in context.Products
  3. join od in context.Orders on pd.ProductID equals od.ProductID
  4. orderby od.OrderID
  5. select new
  6. {
  7. od.OrderID,
  8. pd.ProductID,
  9. pd.Name,
  10. pd.UnitPrice,
  11. od.Quantity,
  12. od.Price,
  13. }).ToList();

Inner Join with AND condition

Sometimes, you need to apply inner join with and condition. To write query for inner join with and condition you need to make two anonymous types (one for left table and one for right table) by using new keyword and compare both the anonymous types as shown below:
  1. DataContext context = new DataContext();
  2. var q=from cust in context.tblCustomer
  3. join ord in context.tblOrder
  4. // Both anonymous types should have exact same number of properties having same name and datatype
  5. on new {a=(int?)cust.CustID, cust.ContactNo} equals new {a=ord.CustomerID, ord.ContactNo}
  6. select new
  7. {
  8. cust.Name,
  9. cust.Address,
  10. ord.OrderID,
  11. ord.Quantity
  12. };
  1. // Generated SQL
  2. SELECT [t0].[Name], [t0].[Address], [t1].[OrderID], [t1].[Quantity]
  3. FROM [tblCustomer] AS [t0]
  4. INNER JOIN [tblOrder] AS [t1] ON (([t0].[CustID]) = [t1].[CustomerID]) AND ([t0].[ContactNo] = [t1].[ContactNo])

What is REST : Representational State Transfer

REST stands for Representational State Transfer. The term was introduced by Roy Fielding in his doctorial dissertation. REST is an architectural style for designing networked applications. It is an alternate to using complex mechanisms like COBRA, RPC, and SOAP to connect between client and server. REST makes communication between remote computers easy by using the simple HTTP protocol which support for CRUD (Create, Read, Update, and Delete) operations on the server. In a way, our World Wide Web is also based on the REST architecture.
In a nutshell, REST is based on the representation of resources. A resource is an object that we can access over the World Wide Web. It can be a document, an image, or anything. When we request a resource (an object) from a server, the server returns the representation of that resource. In REST architecture, a client requests an operation (CRUD) on an object (resource) on the server, and the server returns data as per requirements.
Example – Let us consider a Web Service that returns Employee information. The Web Service responds to client calls by polling a database and returning a result. In classical Web Services or WCF Services, we would have a method exposed to clients, like GetEmployee(). The REST architecture is different from this as it does not work with the methods but with nouns (resources / objects) and allow verbs (HTTP Methods) to operate on them.
So if we want to get Employee information, we send an HTTP GET on the object Employee rather than query a method like GetEmployee(). The advantage is manifold, the most important being the power and flexibility that we get in our hands to play around with the object.
For further reading, see the References section at the end of the article. I will not go into the details of explaining REST, rather concentrate on how to code one from scratch.
Why use REST?
Let us consider a practical example. Imagine that you have to build a Web Service which should be cross functional and should be able to be consumed by any client. Traditional Web Services in .NET have to be consumed using a proxy. What if the client does not know how to create a proxy? Imagine that your Web Service needs to be consumed by a client running on an iPhone or Android. As far as I know, Objective C does not know how to create a proxy. It only knows to send basic HTTP verbs – GET, PUT, POST, and DELETE – to the server and expect XML or string as response. Enter the world of REST!!
HTTP verbs
At this time, it is worthwhile to revise our basic HTTP verbs. I will just give a brief introduction. Detailed information is easily available over the internet.
GET – GET is one of the simplest HTTP methods. Its main job is to ask the server for a resource. That resource may be an HTML page, a sound file, a picture file (JPEG) etc. We can say that GET method is for getting something from the server. In GET method, the data we send is appended to the URL.
Example:
GET /path/file.html HTTP/1.0
From: someuser@jmarshall.com
User-Agent: HTTPTool/1.0
POST – The POST method is used to submit data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource, or the updates of existing resources, or both.
Example:
POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies
PUT – The PUT method is used to submit data to be updated (e.g., from an HTML form) to the identified resource. Like the POST method, the data is included in the body of the request.
DELETE - The DELETE method is used to delete a specific resource.