Saturday, 28 June 2014

Simple Explaination of MVC Architectural Pattern with Example


Understanding the MVC Architectural Pattern
Assumptions:
1..NET4 and vs2010/above is installed on system. 
 Code Download: Click Here to download entire solution
2. Knowledge .Net Basics with C#
Note : I am using Microsoft vs2010 MVC template for creating this Article Gallery Application  Next Series i will demo how we can separate Model and Database Repository to fallow Separation of Concern [SOC]

How ASP.NET MVC Works

Introduction

MVC is the just separation of model, view and controller It's simply a way to Avoid mixing code from the three categories into one class.MVC is architectural pattern which separates the representation and the user interaction. It's divided in three broader sections, "Model", "View" and "Controller". Below is how each one of them handles the task
  • The "View" is only responsible for look and feel.
  • Model represents the real world object and provides data to the "View".
  • The "Controller" is responsible to take the end user request and load the appropriate "Model" and "View".
IMPORTANT POINT: MVC CAN ONLY ACT AS 3-LAYER ARCHITECTURE IN CASE OF SMALL APPLICATION DEVELOPMENT ,BUT IN CASE OF ENTERPRISE/BIG APPLICATIONS MVC( MODEL, VIEW AND CONTROLLER ) ARE JUST 3 LAYERS OF PRESENTATION LAYER.

Complete flow of MVC?
To understand the the power of MVC you need to understand the Life Cycle, I could go in to great detail about the ASP.NET Life cycle, but I have found a number of very good articles already providing good amount of information on the Life Cycle.  Before going to the pages here is a simple flow diagram of the steps the MVC process goes through
Below are the steps how control flows in MVC (Model, view and controller) architecture:-
  1. All end user requests are first sent to the controller.
  2. The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  3. The final view is then attached with the model data and sent as a response to the end user on the browser.
ASP.NET MVC represents a simpler, more testable framework for developing web applications in Microsoft .NET.When people reference the acronym MVC, they are most likely referring to the software design pattern. Model-View-Controller is a user interface design pattern that separates display , data, and flow of control into different objects  The view represents the screen and user input, the controller acts to coordinate the input/output from the view, and the model is the data structure that is passed between the two as shown in below figure 1. The pattern helps separate the display, interaction, and data logic.
URL Routing Engine:
In the standard ASP.NET model (or Post-back model), the URLs map directly to the physical files
So when we make a request to a page, say ViewArticle.aspx, the run-time compiles that page and returns the generated HTML back to IIS to be displayed by the client browser. So we have a one-to-one relationship between the application URLs and the page.But in the MVC framework, the URLs map to the controller classes.
Therefore, the URL is sent to IIS and then to ASP.NET run-time, where it initiates a controller class based on the URL, using the URL routes, and the controller class then loads the data from the model, with this data finally being rendered in the view as per convention rather than configuration The controller classes uses URL routing to map the URLs, which in simpler terms means rewriting URL. We can set up the rules for which URL is to be routed to which controller class. The routing will pick up the appropriate controller and pass in the query string variables as necessary.
Open the global.asax.cs file and examine the following code:
public class MvcApplication : System.Web.HttpApplication
            { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("
{resource}.axd/{*pathInfo}");
            routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new
            { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } protected
            void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); } } 
The RegisterRoutes() method contains the URL mapping routes. Initially we have only the default rule set:
routes.MapRoute(name: "Default" ,url:"{controller}/{action}/{id}",defaults:
            new { controller ="Home", action = "Index", id = UrlParameter.Optional }); 
This URL mapping engine comes from System.Web.Routing.dll, which can be used independently, without the ASP.NET MVC framework, That mean URL routing can be used with  standard ASP.NET web applications also.
The MapRoute() method, which handles URL routing and mapping, takes three arguments:
  1. Name of the route (string)
  2.  URL format (string)
  3.  Default settings (object type)
In our case, we named the first route "Default" (which is the route name) and then set the URL as:
Controller/action/id
The Controller here is the name of the controller class. action will be the method that needs to be invoked inside that controller class. id would be the parameters that need to be passed, if any. In the default arguments, we create a new object and call it "Home", set the action to Index, and do not pass parameters to it
The var keyword and anonymous types: We normally use classes to wrap behavior and properties, but in C# 3.0 and above, we can create the types anonymously without needing to create classes for them. This can be useful when we need to create light weight classes that have only read only properties. We can use the anonymous syntax to create those types without the need to create a class for them. We can use the new " var " keyword to hold such anonymous types, for example:
var ch = new {readOnlyProperty1 =value1,readOnlyProperty2
            = value2 };
It is important that we name and assign a value to each of the properties that we are creating. Like
var ch = new {Name ="Shabir",City "Bangalore" };
What will be the type of the properties?
they will automatically be cast to the data types of the values of the properties specified. The anonymous types will always be derived from the base object class directly. They can only be used within class members and cannot be passed as method arguments (unless they are boxed), return values, or be specified as class-level variables. Once the type is created, it cannot be changed into another type.So we create a new anonymous type as the last argument of the MapRoute() method, passing in variable defaults with three properties, namely controller, action, and parameter.Now have the Default.aspx page under the root directory, which acts as a redirecting page to the main home page of the site (which is /View/Home/Index.aspx). We cannot directly set that as the "default" page since we are using URL routes to process pages instead of using physical files in the URLs. So in the code-behind of our Default.aspx page, we have a simple redirect:
public void Page_Load
(object sender, System.EventArgs e) { Response.Redirect("~/Default"); } 
So the run time will first set up routes in the global.asax page, then it will process the Default.aspx page. Here it faces a redirect to this URL: /Home.

MVC With EXAMPLE

Fallow below steps to open and create solution
1. Open Vs2010/Above (better open as Admin) & choose MV4 Template from list and name it as per your naming convention.For me Faith.MVC.Sample & press OK
2. You will see below screen .Just choose Internet Application Icon from List like shown below & press OK
3.You will see below screen with default MVC solution like shown  below
4.Now you have default solution open .The Model View Controller (MVC) pattern is a popular design pattern used in many software systems  because it  separates a software module into three distinct layers each with a specific role while  using visual studio you will get below shown solution created by default(below).
Model:
Models represent data. A model can be as simple as a single object or a complex type with many collections of objects within it. The model should not include implementation details. A model may have many associated views.

View:

The view typically represents a user interface component that is bound to a model. The view can display the data and allow a user to modify the data. The view should always reflect the state of the model.

Controller:

The controller provides a mechanism for the user to interact with a system by defining how the user interface reacts to user input. It is responsible for exchanging and interpreting messages between the view and the model. Let us assume we are going to create Article Gallery with below option using Database First Approach  Adding Article
  • Updating Article
  • Deleting Article
  • View Article
  • Search Article
  • View Article Detail
Let us first create Model.
Designing a Data Model
In MVC, M stands for model, and it’s the most important character in the pattern. Your model is a software representation of the real-world objects, processes, and rules that make up the subject matter, or domain, of your application. It’s the central keeper of data and domain logic (i.e., business processes and rules).  You don’t need much of a domain model for the Article Gallery application, but there is one obvious type of model object that we’ll call Article..

Adding a Model Class

For below explanation i will be using Database First Model.Before i start creating model i just want to say that there are  three approaches to using Entity Framework (EF) – Model First, Database First and Code First. Here you see the explanation of each.
Database First :In the database first approach, we are creating the entity framework from an existing database. We use all other functionality, such as the model/database sync and the code generation, in the same way we used them in the Model First approach
Model First:In the Model First approach, the database model is created first using the ORM designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model. .
Code First: In Code-First Approach, we create the classes first and then generate the database from the classes directly. In code first, we won’t use the Entity Designer (for editing .edmx files) at all.
So when should one choose one method over the others? Here is a simple comparison of the advantages all three approaches. Fact is that all three approaches lead to creation of Model and using any of these approaches is just matter of taste
Model First:
  • Good support with EDMX designer
  • We can visually create the database model
  • EF generates the Code and database script
  • Extensible through partial classes
  • We can modify the model and update the generated database.
Database First:
  • An existing database can be used
  • Code can be auto-generated.
  • Extensible using partial classes/ T4 templates
  • The developer can update the database manually
  • There is a very good designer, which sync with the underlining database
Code First:
  • There is full control of the model from the Code; no EDMX/designer
  • No manual intervention to DB is required
  • The database is used for data only
Use Solution Explorer to add a new ADO.NET ENTITY DATA MODEL Like shown below
  1. Right Click on Model Folder of the solution explorer and Click on Add-> New Item like show below.Fallow all the steps as shown
Here You can choose existing connection from dropdownlist or just create new connection.
If New Connection is clicked then you will see below screen
After Selecting database just Click on Test Connection button .if you get message like connection succeed like below then proceed
Select tables you want to include in Model.My case I have selected checked tables
Next you will see you model like shown below
Now you can dive into Model1.Designer.cs and see how Entity Framework has generated data access code for you without writing a single line of code.For now we will not touch this model except remembering ObjectContext Class Name which is FaithDbEntities as shown above.We will use this model as is; because we just want to see how MVC Application works .
Adding Controller
Adding Controller  is just simple .You just need to Right click on Controller folder and add New class  as shown below or you can use existing/default HomeController
Adding View
Create Folder with Article name and Right Click on it to Add View like shown below
Recapping whole Example Controller, Model, and View Code
ArticleController:
public class ArticleController : Controller { private
            FaithDbEntities _dbContext = new FaithDbEntities();
 public Article CurrentArticle
            { get; set; } // GET: /Article/ public ActionResult ArticleHome() { return View();
            } [HttpPost] public ActionResult CreateArticle(Article entry) { entry.ArticlePubsDate
            = DateTime.Now; entry.AuthorId =1;//owner always will change in next iteration _dbContext.Articles.AddObject(entry);
            _dbContext.ArticleAuthors.Include("AuthorId"); _dbContext.SaveChanges(); return
            View("Created"); } public ActionResult CreateArticle() { var articleCategoryData
            = _dbContext.ArticleCategories.ToList(); ViewData["_ArticleCategory"] = new SelectList(articleCategoryData,
            // items "ArticleCategoryId", // dataValueField "ArticleCategory1", // dataTextField
            0); return View(); } [HttpPost] public ActionResult EditArticle(Article entry) {
            if (ModelState.IsValid) { //_dbContext.Entry(entry).State = EntityState.Modified;
            _dbContext.SaveChanges(); return RedirectToAction("Index"); } return View(entry);
            } public ActionResult EditArticle(int id) { Article article = _dbContext.Articles.Single(d
            => d.ArticleId == id); if (article == null) { return HttpNotFound(); } var selectedvalue
            = article.ArticleCategoryId; var articleCategoryData = _dbContext.ArticleCategories.ToList();
            ViewData["_ArticleCategory"] = new SelectList(articleCategoryData, // items "ArticleCategoryId",
            // dataValueField "ArticleCategory1", // dataTextField selectedvalue); ViewData["Article"]
            = article; return View(article); } public ActionResult ViewArticles() { using (var
            context = new Faith.MVC.DAL.FaithDbEntities()) { return View(context.Articles.ToList());
            } } public ActionResult ViewArticleDetail(int id) { CurrentArticle = _dbContext.Articles.Single(d
            => d.ArticleId == id); return View(CurrentArticle); } public ActionResult DeleteArticle(int
            id) { CurrentArticle = _dbContext.Articles.Single(d => d.ArticleId == id); if
            (CurrentArticle == null) return View("RecordNotFound"); Delete(); _dbContext.SaveChanges();
            return View("Deleted"); } [NonAction] public void Delete() { try { _dbContext.Articles.DeleteObject(CurrentArticle);
            _dbContext.SaveChanges(); } catch (DataException ex) { throw ex; } } public ActionResult
            SearchIndex(string articleTitle, string searchText) { var ArtLst = new List();

            var ArtQry = from d in _dbContext.Articles
                           orderby d.ArticleId
                           select d.ArticleTitle;
            ArtLst.AddRange(ArtQry.Distinct());
            ViewBag.movieGenre = new SelectList(ArtLst);

            var articles = from m in _dbContext.Articles
                         select m;

            if (!String.IsNullOrEmpty(searchText))
            {
                articles = articles.Where(s => s.ArticleTitle.Contains(searchText));
            }

            if (string.IsNullOrEmpty(articleTitle))
                return View(articles);
            else
            {
                return View(articles.Where(x => x.ArticleTitle == articleTitle));
            }

        }

      
    }
       
CreateArticle.cshtml
@model Faith.MVC.DAL.Article @{ ViewBag.Title = "CreateArticle";
            Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Article Gallary</h2>
            <form method="post" action=""> <fieldset> <legend>Add Article</legend>
            <table> <tr><td>@Html.LabelFor(m => m.ArticleTitle)</td>
            <td> @Html.TextAreaFor(m => m.ArticleTitle, new { cols = "40", rows = "1"
            })</td></tr> <tr><td>@Html.LabelFor(m => m.ArticleCategoryId)</td>
            <td> @Html.DropDownListFor(m => m.ArticleCategoryId, ViewBag._ArticleCategory
            as SelectList) </td></tr> <tr><td>@Html.LabelFor(m =>
            m.AuthorEmailId)</td> <td>@Html.TextBoxFor(m => m.ArticleTitle) </td></tr>
            <tr><td>@Html.LabelFor(m => m.ArticleIntroduction)</td> <td>
            @Html.TextAreaFor(m => m.ArticleIntroduction, new { cols = "50", rows = "6" })</td></tr>
            <tr><td>@Html.LabelFor(m => m.ArticleBody)</td><td> @Html.TextAreaFor(m
            => m.ArticleBody, new { cols = "70", rows = "10" })</td></tr> <tr><td>@Html.LabelFor(m
            => m.ArticleSummary)</td> <td> @Html.TextAreaFor(m => m.ArticleSummary,
            new { cols = "70", rows = "4" })</td></tr> <tr><td><input
            type="submit" value="Submit Article" /></td><td></td></tr>
            </table> </fieldset> </form> 
ViewArticle.cshtml
@{ ViewBag.Title = "View Articles"; Layout = "~/Views/Shared/_Layout.cshtml";
            } <h2>@ViewBag.Message</h2> <header> <h3>Article Galary</h3>
            </header> <table> @using (Html.BeginForm("SearchIndex","Article",FormMethod.Get)){
            <tr><td> Title: @Html.TextBox("SearchText")</td> <td><input
            type="submit" value="Search" style ="height:26px;width:auto" /></td></tr>
            } </table> <br /> <table class="tablecss"> @foreach (var article
            in Model) { <tr class="odd"> <td> @Html.ActionLink("Edit", "EditArticle",
            new { id = article.ArticleId }) | @Html.ActionLink("Details", "ViewArticleDetail",
            new { id = article.ArticleId }) | @Html.ActionLink("Delete", "DeleteArticle", new
            { id = article.ArticleId }) <img src="../../Images/Photo/shabir.jpg" alt="" width="42px"
            height="42px"/> </td> <td><b>Published date:</b> @article.ArticlePubsDate
            <br /> <b>Title:</b><a href="@article.ArticleURL">@article.ArticleTitle</a><br
            /> <b>Summary:</b><i>@article.ArticleSummary </i> <b
            style ="color:Orange">@Html.ActionLink("Read more", "ViewArticleDetail", new
            { id = article.ArticleId })>></b> </td> </tr> 
ViewArticleDetail.cshtml
@model Faith.MVC.DAL.Article @{ ViewBag.Title = "ViewArticleDetail";
            Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="page"> <div class="maincontent">
            <div class="article"> <div id="panSummary" class="summarybox"> <ul>
            <li>Av rating:<img id="imgRating1" alt="" src="../../Images/icon_plain_3stars.gif"
            style="height:13px;width:70px;border-width:0px;"/></li> <li>Total
            votes: 135</li> <li>Total comments: 29</li> </ul> <ul>
            <li><img id="imgEmail" alt="" src="../../Images/icon_email_13x11.gif" style="height:11px;
width:14px;border-width:0px;"/> 
            <a id="lnkEmail" href="">send to a friend</a></li> <li><img
            id="imgPrint" alt="" src="../../Images/icon_print_13x11.gif" style="height:11px;width:14px;border-
width:0px;"/> 
            <a id="lnkPrint" href="" target="_blank">printer friendly version</a></li>
            </ul><ul><li> <img alt="" id="imgDownload" alt="" src="../../images/icon_code_14x11.gif"
            style="height:11px;width:14px;border-width:0px;"/> Downloads <ul> <li><a
            id="Relatedarticles_lnkLink" href="">Code.zip</a></li> </ul></li>
            </ul> </div> <img id="imgAuthor" class="authorpicture" align="left"
            src="../../Images/Photo/shabir.jpg" alt="shabirhakim" style="border-width:0px;"/>
            <div class="articletitle">@Model.ArticleTitle</div> <div class="date">@Model.ArticlePubsDate</div>
            <div class="author">by <a id="ctl00_MainContent_lnkAuthor" rel="author"
            href="https://www.shabirhakim/author//">@Model.AuthorEmailId</a></div>
            <div class="clear"/> <h3>Introdcution</h3><br /> <div
            class="articleintro"> @Model.ArticleIntroduction </div> <hr /> <h3>Body</h3><br
            /> <div class="articledetail"> @Model.ArticleBody </div> <h3>Summary</h3><br
            /> @Model.ArticleSummary <br /> <br /> <div class="authorpanel"
            > <img id="imgAuthor" class="authorpicture" src="../../Images/Photo/shabir.jpg"
            alt="shabirhakim" align="left" style="border-width:0px;"/> <p><strong>Author
            profile:</strong> <a id="Author1_lnkName" href="#">shabirhakim</a></p>
            <p>shabirhakim is a .NET development instructor which focuses on using XML,
            ADO.NET and Web Services in Microsoft’s .NET platform.</p> <p><a
            id="Author1_lnkSearch" href="">Search for other articles by shabirhakim</a></p>
            <div class="clear"></div></div> </div> <div id="panToRate"
            class="rating"> <h3>   Rate this article:</h3> <br/>
            <table border="0" > <tbody><tr> <td><input id="radRating1"
            type="radio" name="radRating" value="radRating1"/><br/>Poor</td>
            <td><input id="radRating2" type="radio" name="radRating" value="radRating2"/><br/>OK</td>
            <td><input id="radRating3" type="radio" name="radRating" value="radRating3"/><br/>Good</td>
            <td><input id="radRating4" type="radio" name="radRating" value="radRating4"/><br/>Great</td>
            <td><input id="radRating5" type="radio" name="radRating" value="radRating5"/><br/>Must
            read</td> <td> <input type="button" name="btnRateArticle" id="btnRateArticle"
            value="Rate" /> </td></tr> </tbody></table> </div>
            </div> </div> 
Understanding MVC Conventions
There are two kinds of conventions in an MVC project. The first kind is really just suggestions as to how you might like to structure your project. For example, it is conventional to put your JavaScript files in the Scripts folder. This is where other MVC developers would expect to find them, and where Visual Studio puts the initial JavaScript files for a new MVC project. But you are free to rename the Scripts folder, or remove it entirely and put your scripts anywhere you like. That would not prevent the MVC Framework from running your application.The other kind of convention arises from the principle of convention over configuration, which was one of the main selling points that made Ruby on Rails so popular. Convention over configuration means that you don’t need to explicitly configure associations between controllers and their views, for example. You just follow a certain naming convention for your files, and everything just works. There is less flexibility in changing your project structure when dealing with this kind of convention. The following sections explain the conventions that are used in place of configuration.

Following Conventions for Controller Classes

Controller classes must have names that end with Controller, such as ProductController, AdminController, and HomeController. When referencing a controller from elsewhere in the project, such as when using an HTML helper method, you specify the first part of the name (such as Article), and the MVC Framework automatically appends Controller to the name and starts looking for the controller class.
Following Conventions for Views
Views and partial views go into the folder /Views/Controllername. For example, a view associated with the ProductController class would go in the /Views/Product folder. The MVC Framework expects that the default view for an action method should be named after that method. For example, the default view associated with an action method called List should be called List.cshtml. Thus, for the List action method in the ProductController class, the default view is expected to be /Views/Product/List.cshtml. The default view is used when you return the result of calling the View method in an action method,like this:
 return View();
You can specify a different view by name, like this:
return View("MyOtherView");
Notice that we do not include the file name extension or the path to the view. When looking for a view, the MVC Framework looks in the folder named after the controller and then in the /Views/Shared folder. This means that we can put views that will be used by more than one controller in the /Views/Shared folder and the framework will find them.

Following Conventions for Layouts

The naming convention for layouts is to prefix the file with an underscore (_) character, and layout files are placed in the /Views/Shared folder. Visual Studio creates a layout called _Layout.cshtml when all but the Empty project template is used. This layout is applied to all views by default through the /Views/_ViewStart.cshtml file.If you do not want the default layout applied to views, you can change the settings in_ViewStart.cshtml (or delete the file entirely) to specify another layout in the view, like this:
@{ Layout = "~/Views/Shared/MyLayout.cshtml" } Or you
            can disable any layout for a given view, like this: @{ Layout = null; } 

What Is a Persistence Framework?


A persistence framework is a library used to simplify accessing and storing information. In practice, this means how we write our code to communicate with the relational database management system (RDMS). The current trend in the industry is to use object-relational mapping (ORM) persistence frameworks. These are abstract things such as tables, columns, and rows, and they allow us to work primarily with objects. Popular open source ORMs for .NET include  :
  1. NHibernate
  2. Entity Framework
  3. LINQ to SQL

Deciding Between MVC and Web Forms

Problem:  Organisations which are  using  web forms from several years. Suddenly shifting  from webfarm to MVC will be bit tough and hasty decision because  MVC has got steep learning curve and complexity  in Solution architecturing. I believe organisations  need help deciding whether to stick with Web Forms or dive into MVC. If MVC is not yet a standard development framework in your organization, you may need to justify this design decision to management or an enterprise architecture team.
Decision: Let us take detailed look at the advantages and disadvantages of each,and make the case for MVC.First, I have to say that Web Forms gave us a great and smooth run for long. I have used Web Forms on many successful projects.Many of them are still in active use almost five years after they were initially deployed. So ,Fact is that WebForm are alive and will remain alive in market parallel to MVC because It has got huge advantages  like its rich control support and  rich server side event model.Reality is that No technology is perfect. They all have things they can do very well, and areas where they lack and can use improvement. This section takes an honest look Web Forms and MVC, and discusses the benefits and drawbacks of each. 

Web Forms Disadvantages

• Hard and Toughest part is post-backs:
• ASP.NET controls are not as effective as modern client-side libraries: The large library of UI widgets that come with Web Forms, which seemed like such an asset a few years ago, are also falling out of favor. The JavaScript UI libraries that are freely available from jQuery and others are just plain better than what is available in ASP.NET. They render faster, do not rely on the dreaded ASP.NET view state, and are beautiful. While many of the controls have been updated in the latest release of ASP.NET, most of them still use deprecated rending techniques such as using HTML tables for layouts. They are also difficult, if not impossible, to program against from client-side code.
• The code-behind pages often break separation of concerns: While a disciplined programmer can create clean code-behind pages, in many cases, developers break the separation of concerns by manipulating the user interface in the code-behind page, or even worse—directly manipulating the database from the code behind. This often leads to huge, fragile, unmaintainable, and untestable code.
• View State: Web Forms uses a concept known as view state, in which a hidden field contains the values of all server-side controls, encoded in a big nasty string. This data is sent on every postback, which slows response times and increases bandwidth usage. For pages that use controls such as a grid view, the view state can be hundreds of kilobytes.
• Client-side code is difficult to work with: The client-side code generated by Web Forms is difficult to read and very difficult to code against. First, each UI Widget that you drag onto a page is attached to a DLL with possibly 20 embedded script files. In many cases, using just one of these controls on a page will lead to all 20 of these scripts being included on your page in
• Another pain point for client-side developers is the automatic naming convention used for client-side elements With the default setting, you get ids in the form of ctl00_LoginView1_LoginName1. For nested UI elements, it gets even worse. ASP.NET 4 offers a mechanism to aid in this situation by allowing you to specify how the client ID can be generated.
• Code-behind pages can't be tested with automated testing tools: Code-behind pages are simply not designed for this scenario. There is no easy way to abstract the code-behind pages so that a unit test framework can be used. If you were planning on using a test-driven development(TDD) approach with Web Forms, you will have a difficult time.

MVC Disadvantages

• Learning curve: If you are coming from Web Forms, there is a substantial learning curve associated with moving to MVC. Having to learn a new technology on a deadline is never simple nor can be achived easily.
• More complex: The MVC code separates the code that makes up a page into a minimum of three files. If you are not planning on doing unit testing, and don’t like HTML coding, MVC may not be the best choice.I mean when development cycle includes test driven development TDD  then MVC is the best choice otherwise it sucks..
• No drag-and-drop form creation: If you use the MVC Framework, you will be hand-coding your HTML. In fact, Visual Studio does not even offer a visual designer for MVC Views when using the Razor view engine. For most teams, the learning curve is hardest  to move past. For Prototyping there is no support in Razor .
Difference between LINQ to SQL and Entity Framework
LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. More specifically, LINQ to SQL has been developed to target a rapid development scenario against Microsoft SQL Server where the database closely resembles the application object model and the primary concern is increased developer productivity. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.

  1. LINQ to SQL supports a wide breadth of abstractions
  2. LINQ to SQL support domain Model
  3. Linq to SQL is only for SQL
  4. LINQ to SQL is simple to use
  5. LINQ to SQL is used for rapid development.
  6. LINQ to SQL class uses the mapping only for the single table
  7. LINQ to SQL generate only dbml file

LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
  1. Entity framework supports a high level of abstraction.
  2. Entity framework support conceptual data mode.
  3. Entity Framework will have ability to target different database engines in addition to Microsoft SQL Server.
  4. Entity framework is complex to use.
  5. Entity framework is slower development but has more capabilities.
  6. Entity framework map a single class to multiple tables
  7. Entity framework generate the three xml files csdl, msl and ssdl. 
Conclusion :
.NET is going on along with both patterns (MVC & Webforms).Now all depends on need and requirement.So,based on need we can pickup right one.

How these Articles will be structured

During the course of these articles, I m going to explain how to Architect End to End Application using MVC with Entity Framework, starting with the ones at the beginning of the MVC and finishing with the Complate Application Architecture includes. :
  1. Seperating Model and DataAccess from Entity Model
  2. Applying Validation Using the ASP.NET MVC 4
  3. ASP.NET MVC Defining an application architecture:
  4. ASP.NET Application Development Using MVC
  5. How do architect an ASP.Net MVC app with EF?
  6. Using T4 to Generate POCO Classes
Thus far we have seen an overview of the entire ASP.NET MVC Application, and should now have a feel for the huge number of opportunities available to extend and customize how the framework behaves. We've also seen that not all extensibility hooks are created equal, and there are some which are more useful than others. Now that we're all on the same page, the next article will cover how to Seperating Model and DataAccess from Entity Model .
Separating Model from  ADO.NET Entity Data Model
Assumptions:
1..NET4 and vs2010/above is installed on system.
 

Code Download: Click Here to download entire solution

IntroductionI wrote a post a last weeks about Understanding MVC Pattern . If you have read that post first (it might be a good idea) you can click here to read it now.Since it was posted, I have noticed that a few people visit the post every day and they might be waiting for next post.At, the end of my article i have clearly mentioned that i will be cleaning this application in future posts . So, as  promised, I am going to fallow some steps to achieve this. So,this post will be  useful as well as helpful i hope.

Create the Solution in Visual Studio2010

I will modify existing solution or you can create new one in a same way for Article Gallery Application which is developed to keep track of  members/authors and their respective articles . if you have not gone throught it just click to see here Article Gallery Application . So to begin with, let’s create a modify existing solution and then add projects to it that will make the different layers of our application. Using Visual Studio,add in the following projects like shown below


Here you see list of Projects(layers) to the solution:

FaithModel– This layer will contain the POCO objects
Data Access Layer – This layer will interact with the database and will contain our Entity Framework file FaithDataLayer in my case
Business Access Layer – This layer calls the data layer and implements business rules(FaithBusinessLayer) in my case
Service Layer – This layer contains the actual WCF or Other service that can be accessed by external websites  (FaithServiceLayer) in my case
Web Layer – This is a MVC website that will be accessed from browser (Faith.MVC.Sample) in my case
For Solution layers, you can name your projects whatever you want as long as you know what each layer is for. Model, Datalayer, BusinessLayer .... are just naming conventions that I have choose.
This is what it looks like in my solution explorer:

Entity Framework Model and POCO’s

Now right click on the FaithDataLayer project in your solution and select Add > New Item … When the dialog box appears, click on " FaithDataLayer" in the "Installed Templates" section like below

Once that has been done, click on the "ADO.NET Entity Data Model" name the file as per your naming convention and then save it by clicking "Add".
At this point, the "Entity Data Model Wizard" appears. Fallow below steps
  1.  Select "Generate From Database" on the "Choose Model Contents" page.
  2.  Click Next
  3. Click on "New Connection" and then use the "Connection Properties" dialog to build the connection string to your database. I recommend that you use "SQL Server Authentication" with an account that is set up with only the necessary permissions for your applications
  4. Click on Test Connection, if the popup says "Test connection succeeded" then click on the "OK" button
  5. Click on the radio button labeled "Yes, include the sensitive data in the connection string" (this can be encrypted later if you wish)
  6. Click the check box labeled "Save entity connection settings in App.Config as" and then give proper connection a name
  7. Click Next
  8. Select all the database objects that you want to include in the Entity Framework (Mostly database tables)
  9. Again give name for the Model Namespace  as per naming convention
  10. Click "Finish" to Wrap up
Finally our Entity Framework Model is created, But if you will observe whole model is in FaithDataLayer.Now our job is to take the Model out of this layer and push it to separate/independent layer namely FaithModel. Once you are done, your Entity Framework Model should look something like this:

So now that you are looking at the Entity Framework file that you just created, right click on the canvas of the Entity Framework Model. Just select "Add Code Generation Item .


This will bring up another window showing the "Installed Templates" as shown in the screenshot below. Once the "Add New Item" window pops us, we want to select the template called "ADO.NET POCO Entity Generator". Again name it as per your naming convention . I prefer to keep the name the same as what I chose for the Entity Framework itself.


if you cannot find this template installed in your copy of Visual Studio, you can find instructions on searching for and installing templates in Google. Once you save the "ADO.NET POCO Entity Generator", two new files will be created in your data project as shown in below figure. In my project, they are: "FModel.Context.tt" and "FModel.tt". At this point if you will try to compile solution you will not get any problem but there are certain things which need to be observed. First of all, underneath the new template files (with .tt extension), you will see that several new classes based on Model have been added to your DataAccessLayer project, as shown in the graphic below

Each of these new classes maps to an object in your Entity Framework model, which, in turn, map to a table in your database. These files are auto generated each time that the template file is saved, but if you open one up you will see that it is just a  standard class with properties defining each column in the table. You will also notice that they are partial classes. In Future series we will also see how to modify template to customize our classes.
Final Step to Separate your Model(POCO Classes):
Now that the Entity Framework Model is created, we are ready to separate model classes from FaithDataLayer.
To move our POCO’s from the FaithDataLayer to the FaithModel is just Cut and Paste process. Right click on the FaithDataLayer Project  and select FModel.tt to cut and paste the name (FModel.tt). Select "Cut" from the context menu, then right click on the FaithModel project and select paste. All of its associated classes should now have moved to the FaithModel project. Our only problem now is that by moving the template we have broken the link between it and the Entity Framework model upon which it depends to create the POCO classes.  To do so, open the template file(FModel.tt) that is now in the FaithModel project. Just open FModel.tt try to find  line of code that reads something like this:
string inputFile = @"Fmodel.edmx";
And change it to a path where it can find the Entity Framework model over in the FaithDataLayer  project, like so:
string inputFile = @"..\FaithDataLayer\FModel.edmx";
                
When you click save, you will know immediately if this worked. If it did, the class files for your database objects will be regenerated as they should be. If the path that you entered was incorrect or some typing mistake is there, however, you will receive a error . a big error.... If you are on Happy Path i mean if solution builds successfully then just remove System.Data.Entity reference from FaithModel projects if exists then try to build you model project successfully without reference of System.Data.Entity.
Project References Now we are can start adding  project references. Just set references like shown below:

FaithDataAccessLayer Project should Refer FaithModel Project
FaithBusinessLayer Project should Refer FaithDataAccessLayer Project & FaithModel Project
FaithServiceLayer Project should Refer FaithBusinessLayer
FaithModel Project –  No Project References
Note: Please,don't touch or think about Service layer,BusinessLayer  yet because we will use them at right time,i mean in future posts

Hope this helps... 

Friday, 13 June 2014

Difference between Responsive and Adaptive web design?

Overview

The rapid spread of mobile devices has turned the world of web design upside down. Users no longer view web content only on traditional desktop systems, but are increasingly using smartphones, tablets, and other devices with a wide range of dimensions. The challenge for web designers is to ensure that their websites look good not only on a big screen, but also on a tiny phone and everything in between.

Media queries are an excellent way to deliver different styles to different devices, providing the best experience for each type of user. A part of the CSS3 specification, media queries expand the role of the media attribute that controls how your styles are applied. For example, it's been common practice for years to use a separate style sheet for printing web pages by specifying media="print" . Media queries take this idea to the next level by allowing designers to target styles based on a number of device properties, such as screen width, orientation, and so on. 

Difference between Responsive and Adaptive web design?

The hot topic for web developers and website owners is the way that websites can now automatically respond and adapt to any device with any screen size. This new way of web design optimizes the layout of the site to suit the screen size of the device it is being viewed on. There are two ways in which this can be achieve: with Responsive Web Design (RWD) and with Adaptive Web Design (AWD). Visitors to your site will not be concerned about which of the two methods you have used. This can simply come down to your or your designer’s preference. The user will not really notice a visible difference between the two methods but they do differ slightly.Adaptive is bit time consuming and expensive because you have to design multiple page layouts and render them according to device which renders it.

Responsive Web Design (RWD)

The key and important tool or elements that make up a Responsive website are CSS3, media queries, the @media rule, and fluid grids that use percentages to create a flexible foundation. It is also fundamental to use flexible images, flexible videos, fluid type and EM’s instead of pixels. All of these key points allow the responsive website to modify its layout to suit the device.
Responsive design is client-side which means the page is sent to the device browser (the client), and the browser then modifies the appearance of the page in relation to the size of the browser window.

The definition of a responsive website is that it will fluidly alter its composition to improve the accessibility of content depending on the screen size of the browser window.




Adaptive Web Design (AWD)

Adaptive web design uses predefined layouts that have been carefully constructed for a variety of screen sizes. A particular layout is activated when the screen size of the device viewing the website is detected and matched with a style sheet.
Adaptive design is predominantly server side. This means that the web server does all of the work of detecting the various devices and loading the correct style sheet depending on the attributes of the device. As well as the layout changing depending on the size of the screen they can also change depending on conditions like whether the device has a retina display or not. The server can detect this and display high quality images for retina display devices like iPads and lower quality images for standard-definition displays.

The downsides to AWD are that initial construction is very costly as you have a lot of layouts to design. Also to maintain and update all of these layouts can be very time consuming which will therefore cost a lot of money.

The definition of an adaptive website is one that has a set of predefined layouts that are activated when best suited to the device detected by the server.

Similarities and differences

The obvious similarity of both methods is that they improve accessibility of website content on mobile devices and various screen sizes. They also both provide visitors with an enhanced mobile-friendly user experience.

They are different in the way that they deliver the responsive / adaptive design to the user. RWD is dependent on fluid grids and AWD is relying on predefined size layouts. Also the fact that they either use client side or server side is another way in which they differ.

The visible difference is that responsive design will fluidly alter its layout while you resize your browser window whilst adaptive design will load a specific layout for the device you’re viewing the site on. If you resize your window with an adaptive website it will jump to a different breakpoint when you reach a screen size that suits another predefined layout.

Responsive Web Design Basics

Truth is that Web started with only webpages. We never thought that there can be anything apart from computers which will access the web page.Simple,We were not ready for other devices,When suddenly  use of mobile devices to browse the web increased ,nothing was visible on small devices properly web isn't optimized for those mobile devices. Mobile devices are often constrained by display size and require a different approach to render data on screen.
 Let us start thinking about how to optimize our existing or new web for mobile devices..
First and foremost thing is to use VIEWPORT TAG .

How to set the viewport

Pages optimized for a variety of devices must include a meta viewport element in the head of the document. A meta viewport tag gives the browser instructions on how to control the page’s dimensions and scaling.

 In order to attempt to provide the best experience, mobile browsers will render the page at a desktop screen width (usually about 980px, though this varies across devices), and then try to make the content look better by increasing font sizes and scaling the content to fit the screen. For users, this means that font sizes may appear inconsistently and they have to double-tap or pinch-zoom in order to be able to see and interact with the content.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
 
Using the meta viewport value width=device-width instructs the page to match the screen’s width in device independent pixels. This allows the page to reflow content to match different screen sizes, whether rendered on a small mobile phone or a large desktop monitor.
Some browsers will keep the page’s width constant when rotating to landscape mode, and zoom rather than reflow to fill the screen. Adding the attribute initial-scale=1 instructs browsers to establish a 1:1 relationship between CSS pixels and device independent pixels regardless of device orientation, and allows the page to take advantage of the full landscape width.

Ensure an accessible viewport

In addition to setting an initial-scale, you can also set the minimum-scale, maximum-scale and user-scalable attributes on the viewport. When set, these can disable the user’s ability to zoom the viewport, potentially causing accessibility issues.

Size content to the viewport

On both desktop and mobile devices, users are used to scrolling websites vertically but not horizontally, and forcing the user to scroll horizontally or to zoom out in order to see the whole page results in a poor user experience.

FINALLY -----

 

 

POINTS TO REMEMBER WHILE DESIGNING RESPONSIVE WEBSITE

  • Use meta viewport tag to control the width and scaling of the browsers viewport.
  • Include width=device-width to match the screen's width in device independent pixels.
  • Include initial-scale=1 to establish a 1:1 relationship between CSS pixels and device independent pixels.
  • Ensure your page is accessible by not disabling user scaling.
  • Do not use large fixed width elements.
  • Content should not rely on a particular viewport width to render well.
  • Use CSS media queries to apply different styling for small and large screens.
  • Media queries can be used to apply styles based on device characteristics.
  • Use min-width over min-device-width to ensure the broadest experience.
  • Use relative sizes for elements to avoid breaking layout.
  • Media queries can be used to apply styles based on device characteristics.
  • Use min-width over min-device-width to ensure the broadest experience.
  • Use relative sizes for elements to avoid breaking layout.
Below is a list of  most popular devices, along with their resolutions and display sizes.
Manufacturer Model Screen Size Resolution Type
Acer Iconia Tab 10.1″ 1280×800 Tablet
Amazon Kindle Fire 7″ 1024×600 Tablet
Apple iPad 9.7″ 1024×768 Tablet
Apple iPad 2 9.7″ 1024×768 Tablet
Apple iPad 3 9.7″ 2048×1536 Tablet
Apple iPhone 3GS 3.5″ 480×320 Smartphone
Apple iPhone 4S 3.5″ 960×640 Smartphone
Apple iPhone 5 4″ 640×1136 Smartphone
ASUS Transformer TF101 10.1″ 1280×800 Tablet
ASUS Transformer Prime TF201 10.1″ 1280×800 Tablet
Barnes & Noble NOOK 7″ 1024×600 Tablet
BlackBerry Playbook 7″ 1024×600 Tablet
BlackBerry Torch 9800 3.2″ 480×360 Smartphone
BlackBerry Torch 9810 3.2″ 640×480 Smartphone
Colby Kyros 7″ 800×480 Tablet
HP TouchPad 9.7″ 768×1024 Tablet
HTC Amaze 4G 4.3″ 960×540 Smartphone
HTC Evo 3D 4.3″ 960×540 Smartphone
HTC Flyer 7″ 1024×600 Tablet
HTC Sensation 4G 4.3″ 960×540 Smartphone
HTC Thunderbolt 4.3″ 480×800 Smartphone
Lenovo IdeaPad A1 7″ 1024×600 Tablet
Lenovo ThinkPad 10.1″ 1280×800 Tablet
LG G2x 4G 4″ 800×400 Smartphone
LG G-Slate 8.9″ 768×1280 Tablet
Motorola Droid BIONIC 4.3″ 540×960 Smartphone
Motorola Droid RAZR 4.3″ 540×960 Smartphone
Motorola Droid Xyboard 10.1 10.1″ 1280×800 Tablet
Motorola Xoom 10.1″ 1280×800 Tablet
Nokia Lumia 900 4.3″ 480×800 Smartphone
Samsung Brightside 3.1″ 240×320 Smartphone
Samsung Epic 4G Touch 4.52″ 800×480 Smartphone
Samsung Exhibit 4G 3.5″ 480×800 Smartphone
Samsung Focus Flash 3.7″ 480×800 Smartphone
Samsung Galaxy S 4G 4″ 480×800 Smartphone
Samsung Galaxy S II 4.52″ 800×480 Smartphone
Samsung Galaxy S III 4.8″ 1280×720 Smartphone
Samsung Galaxy Tab 7″ 1024×600 Tablet
Samsung Galaxy Tab 7.7 7.7″ 1280×800 Tablet
Samsung Galaxy Tab 10.1 10.1″ 1280×800 Tablet
Samsung Gravity Smart 3.2″ 320×480 Smartphone
Samsung Sidekick 4G 3.5″ 800×480 Smartphone
Sony Tablet S 9.4″ 1280×800 Tablet
T-Mobile MyTouch 4G Slide 3.8″ 800×480 Smartphone
T-Mobile SpringBoard 7″ 1280×800 Tablet
Toshiba Thrive 10.1″ 1280×800 Tablet

Hope you will enjoy...
Shabir Hakim

Friday, 30 May 2014

LIST / TYPES OF MARKUP LANGUAGES



What is a Markup Language

Anything added to a text document that conveys an extra information. Markup languages are the languages that build the web.. That is, if we want to display a word in some format like bold,underline... we use the corresponding markup tags for that particular word. Thus markup describes exactly how the document should appear on the screen or during in report processing. Markup is being used extensively not in computing world but also in electronic documents.
There are two types of markup and hence there exists two types of markup languages. They are procedural and generalized.

Procedural Markup Languages 

- Procedural markup is typified by its use in typesetting and publishing systems, including word processors.

Generalized Markup Languages (GML) - 

There is a major shortcoming in the procedural markup languages. That is, if we intend to extract information from the documents, procedural markup language is found wanting. To meet this challenge, a generalized markup language marks up documents in a different way. The characteristics of these languages are:
1. The elements have logical names, rather than expressing detailed formatting instructions. For example, an element H1 is being used to mark up text that is intended to be a first-level header.
2. Software applications that read documents marked up using a GML are free to present them as they see fit, using formatting rules for particular elements that are either defined internally, or specified elsewhere. When displayed in the screen, the H1 element could be associated with a particular combination of font size and weight.
GML elements usually involve both start and end tags so that the original content is fully contained inside an element. Also there is no hint about how this document should be presented. That is, the web browsers are free to reflect the meanings of these elements. The most commonly used generalized markup language is HTML for web documents and WML for mobile contents.
Generalized Markup Rule-sets Each GML has its own elements, its own rules, and its own particular area of application and in order for the language to function properly as a language, those must all somehow be defined. GMLs are themselves written using Generalized Markup Rule-sets (GMRS), also called meta-languages. The two famous meta-languages are Standard Generalized Markup Language (SGML) and the Extensible Markup Language (XML). In a way, XML is a subset of SGML and WML is derived from XML.
Recently another markup language called as Extensible HTML (XHTML) for future web publishing came out. XHTML is a reformulation of HTML 4 in XML. XHTML has to be designed to avoid some undesirable features of HTML.
Though all these features can be accomplished easily using XML, XHTML has been formulated for keeping the large investment made in HTML.
Below is the list of markup languages :-
  1. Application Markup Language (AppML)
  2. Architecture Description Markup Language (ADML)
  3. Artificial Intelligence Markup Language (AIML)
  4. ASN.1 Markup Language (AML)
  5. Astronomical Instrument Markup Language (AIML)
  6. Astronomical Markup Language (AML)
  7. Automatic Site Markup Language (ASML)
  8. Bean Markup Language (BML)
  9. Better Markup Language (BML)
  10. Bibliography Markup Language (BibML)
  11. Bioinformatics Sequence Markup Language (BSML)
  12. BIOML -  BIOpolymer Markup Language
  13. Board Game Markup Language (BGML)
  14. Business Rules Markup Language (BRML)
  15. Comics Markup Language (ComicsML)
  16. Chemical Markup Language( CML)
  17. Claris Dynamic Markup Language (CDML)
  18. DARPA Agent Markup Language (DAML)
  19. Description Logic Markup Language (DLML)
  20. Directory Services Markup Language (DSML)
  21. Document Template Markup Language (DTML)
  22. Dynamic Hypertext Markup Language (DHTML)
  23. Dynamic Markup Language (DML )
  24. E-business eXtensible Markup Language (ebXML)
  25. Earth Science Markup Language (ESML)
  26. Environmental Markup Language (EML)
  27. Financial Products Markup Language (FpML)
  28. eXtensible Application Markup Language (XAML)
  29. eXtensible rights Markup Language (XrML)
  30. eXtensible Telephony Markup Language (XTML)
  31. eXtensible Graph Markup and Modeling Language (XGMML)
  32. eXtensible Hypertext Markup Language (XHTML)
  33. eXtensible Markup Language (XML) 
  34. FAQ
  35. Farleden Dynamic Markup Language
  36. Field Data Markup Language  (FDML)
  37. FileMaker Dynamic Markup Language (FDML)
  38. Financial products Markup Language (FpML)
  39. Financial Services Markup Language (FSML)
  40. Forms Data Markup Language (FDML)
  41. Form Document Markup Language (FDML)
  42. Forms Definition Markup Language (FDML)
  43. Forms Markup Language (FML)
  44. Gene Expression Markup Language (GEML)
  45. Geometry Description Markup Language (GDML)
  46. Geography Markup Language (GML)
  47. Graffiti Markup Language (GML)
  48. Handheld Device Markup Language (HDML)
  49. Hypertext Markup Language (HTML) 
  50. Human Markup Language (HumanML)
  51. Human Resources Markup Language (HRML)
  52. ICAAP eXtended Markup Language (IXML)
  53. Image Markup Language (IML)
  54. Instrument Control Markup Language (ICML)
  55. Instrument Markup Language (IML)
  56. International Development Markup Language (IDML)
  57. Java Speech Markup Language (JSML)
  58. Karst Markup Language (KML)
  59. Koala Bean Markup Language (KBML)
  60. Lambda Markup Language (LML)
  61. Learning Material Markup Language (LMML)
  62. Legal Extensible Markup Language (LegalXML)
  63. Liturgical Markup Language (LitML)
  64. Log Markup Language (LOGML)
  65. Mail Markup Language (MML)
  66. Maker Markup Language (MML)
  67. Market Data Markup Language (MDML)
  68. Mathematical Markup Language (MathML)
  69. Meaningful Text Markup Language (MTML)
  70. Medical Markup Language (MML)
  71. Mind Reading Markup Language (MRML)
  72. Modest Markup Language (MML)
  73. Multimedia Retrieval Markup Language (MRML)
  74. Music Markup Language (MML)
  75. Outline Processor Markup Language (OPML)
  76. Opera Binary Markup Language(OBML)
  77. Pet Name Markup Language (PNML)
  78. Procedural Markup Language (PML)
  79. Predictive Model Markup Language
  80. Printing Industry Markup Language (PrintML)
  81. Question and Answer Markup Language (QAML)
  82. Quest Markup Language (QML)
  83. Relational-Functional Markup Language (RFML)
  84. Research Information Exchange Markup Language (RIXML)
  85. Rule Markup Language (RuleML)
  86. RESTful API Markup Language (RAML)
  87. Security Assertion Mark-up Language (SAML)
  88. Security Services Markup Language (S2ML)
  89. Simple Markup Language (SML)
  90. Simulation Module Markup Language (SiMMaL)
  91. Spacecraft Markup Language (SML)
  92. Standard Generalized Markup Language (SGML)
  93. Synchronization Markup Language [SyncML]
  94. Synthesis Markup Language
  95. Systems Biology Markup Language (SBML)
  96. Theological Markup Language (ThML)
  97. Transaction Authority Markup Language (XAML)
  98. Trading Partner Agreement Markup Language (TPAML)
  99. Textile markup language (TML)
  100. Transaction Authority Markup Language (XAML)
  101. Turing Machine Markup Language (TMML)
  102. Tutorial Markup Language (TML)
  103. ThML: Theological Markup Language
  104. Universal Rule Markup Language (URML)
  105. Virtual Reality Markup Language (VRML)
  106. Voice Extensible Markup Language (VoiceXML)
  107. Why Markup Language (YML)
  108. Wireless Markup Language (WML)
  109. Yet Another Markup Language (YAML)
Hope you enjoy..... shabir

Thursday, 19 December 2013

Choosing Between ASP.NET Web Forms and ASP.NET MVC?

Introduction

ASP.NET MVC is not a new architecture pattern but the debate still goes on in development circles as to which is better
.So, I just want to try to clear that differences and right usage of patterns. Let we go 10-15 years back and see how web has changed..

History of the web

We've seen a number of changes in web development over the years, not always for the better:
  • Common Gateway Interface (CGI) - Scripting language running outside the web server. Time and resource intensive
  • Microsoft Internet Database Connector (IDC) - Simple wrapper for SQL queries, with templates to format the results
  • Active Server Pages (ASP) - Big step forward but mixture of HTML and code became cumbersome and confusing. Known as "spaghetti code"
  • ASP.NET Web Forms - Compiled web "applications" which hides the "statelessness" of HTTP. Allowed Windows developers to more easily transfer to web developers. Heavy on bandwidth. Untestable.
  • ASP.NET MVC - Reworking of Xerox Smalltalk paradigm from the 1970's. Works WITH statelessness nature of HTTP rather than hiding it. Removes ViewState

Looking Back

We've seen a number of changes in web development over the years, like: Common Gateway Interface (CGI) - Scripting language running outside the web server. Time and resource intensive Microsoft Internet Database Connector (IDC) - Simple wrapper for SQL queries, with templates to format the results Scripting Active Server Pages (ASP) - Big step forward but mixture of HTML and code became bit confusing. Known as ASP.NET Web Forms - Compiled web "applications". It seems to take this bit confusion away We are thinking MVC :)

Choosing Between ASP.NET Web Forms and  ASP.NET MVC?

Fact is that both are just ASP.NET server side technologies known as Active Server Pages .Now where we split them or where is difference ? Actually these are architectural patterns or the way we develop .net web based applications.Both can be the “best choice” for a specific solution depending  application development requirements  . When facing a decision to choose between ASP.NET Web Forms or ASP.NET MVC it is important to know that neither technology is meant to replace the other. Both are running parallely and are used as per project requirement.Now, gap between two is getting filled as Microsoft is parellely including best features of MVC into ASP.NET Webform pattern also.
Some important factors we should consider while making the choice is
  1. If we really need to develop application rapidly, i believe ASP.NET Web Forms pattern is only and best choice
  2. Unit Testing - If  TDD test driven development is not important, ASP.NET web form is best choice.
  3. If Application really doesn't bother about UI scalability(UI for multiple devices) . ASP.NET is again best choice
Apart, there are lots of questions we need to consider before choosing architectural pattern like

  1. Do we have resources with good experience with Web Forms or MVC?
    Because learning MVC is not simple . It has its own learning curve and needs good time to learn.
  2. Be sure that we have people with JavaScript / JQuery based languages because MVC needs to do much with these languages 
  3. Looking for good performance without any postback? MVC is the choice but I know it point to be debated because ASP.NET has option of AJAX

Conclusion

Truth is that choosing  MVC pattern as architectural pattern need to be justified with strong reason otherwise it can never ever end or can lead to project failure because you don't have mature knowledge base yet compared to ASP.NET web-forms.I think you should be equipped with huge experience & information to make a decision what is best for your project. The complete decision depends on your team and project requirement.

How to Build a Full-Stack Web App with Blazor

  Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...