Saturday 28 June 2014

SIMPLE AND QUICK UNDERSTANDING OF ANDROID ENVIRONMENT AND DEVELOPMENT

UNDERSTOOD ANDROID DEVELOPMENT IN 48 HOURS.
Last month, we’ve been building an Android app. Fact is that i was never ever interested in android but later, because of unavailability of resources, i took some job on android development and realized it is just 48 hours of job to understand entire architecture and application development .Coming from a Microsoft-end perspective, I’ll take you through what it’s been like to work with Android and what you can expect as a new Android developer.

Introduction to Android development 

 
 

Android is operating environment based upon the Linux® kernel. Initially, the deployment target for Android was the mobile-phone arena, including smart phones and lower-cost flip-phone devices. However, Android's full range of computing services and rich functional support have the potential to extend beyond the mobile-phone market. Android can be useful for other platforms and applications. The Android platform is the product of the Open Handset Alliance, a group of organizations collaborating to build a better mobile phone. The group, led by Google, includes mobile operators, device handset manufacturers, component manufacturers, software solution and platform providers, and marketing companies. The first Android-capable handset on the market was the G1 device manufactured by HTC and provisioned on T-Mobile. The device became available after 9 months of speculation, where the only software development tools available were some incrementally improving SDK releases.

Here i will  give an introduction  of Android platform and learn how to code a basic like displaying  message in Android application.
The Android platform
Android is a layered environment built upon a foundation of the Linux kernel, and it includes rich functions. The UI subsystem includes:

  • Windows
  • Views
  • Widgets for elements such as edit boxes, buttons,lists, and drop-down lists
Android includes an embeddable browser built upon WebKit, the same open source browser engine powering the iPhone's Mobile Safari browser.
Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack, though not all Android devices are equipped with the required hardware. There is also camera support.

ANDROID ARCHITECTURE
Android operating system is a stack of software components which is divided into five sections  as shown below in the architecture diagram.




Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.
Android Run-time
This is the third section of the architecture and available on the second layer from the bottom. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. The Android run-time also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language.

 Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications.

Applications
You will find all the Android application at the top layer. You will write your application to be installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc. An Android application consists of one or more of the following classifications:

Activities
An application that has a visible UI is implemented with an activity. When a user selects an application from the home screen or application launcher, an activity is started.
Services
A service should be used for any application that needs to persist for a long time, such as a workflow based application,network monitor.
Content providers
Content provider is something where data can be persisted/stored like database or xml. A content provider's job is to manage access to persisted data, such as a SQLite database. If you're developing big application, a content provider is the means of accessing your data.
Broadcast receivers
An Android application may be launched to process a element of data or respond to an event, such as click of button or receipt of a text message,
An Android application, along with a file called AndroidManifest.xml, is deployed to a device. AndroidManifest.xml contains the necessary configuration information to properly install it to the device. For example, whether an application requires access to the network? — this permission must be explicitly stated in the manifest file.
Required tools:What software tools you need to start android development

The easiest way to start developing Android applications is to download the Android studio or Eclipse IDE .We can do  Android development  on Microsoft® Windows®, Mac OS X, or Linux.I assumes you are using the Android studio. Android applications are written in the Java language, but compiled and executed in the Dalvik VM (a non-Java virtual machine). 
If you're a new Android developer, we recommend you download the ADT Bundle to quickly start developing apps. It includes the essential Android SDK components and a version of the Eclipse IDE with built-in ADT (Android Developer Tools) to streamline your Android app development.
Download Eclipse ADT
with the Android SDK for Windows
With a single download, the Eclipse ADT bundle includes everything you need to begin developing apps:
  • Eclipse + ADT plugin
  • Android SDK Tools
  • Android Platform-tools
  • A version of the Android platform
  • A version of the Android system image for the emulator
If you prefer to use an existing version of Eclipse or another IDE, you can instead download the stand-alone Android SDK Tools: After download SDK along with Ellicpse you can see below listed folders in your local system

Just click on ellipse folder and click on ellipse executable file and it will open ellipse IDE as show below.


src
This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon.

gen
This contains the .R file, a compiler-generated file that references all the resources found in your project. You should not modify this file.

bin
This folder contains the Android package files .apk built by the ADT during the build process and everything else needed to run an Android application.

res/
This is a directory for drawable objects that are designed for high-density screens.

res/layout
This is a directory for files that define your app's user interface.

res/values
This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions.

AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines each of its components.
In the next section, you'll create a simple Android application.

Coding a basic application
This section provides a tour of building an Android application. The example application is about as simple as you can imagine: a modified "Hello Android" application. You'll add a minor modification to make the screen background color all white so you can use the phone as a   MySampleApp  .

Create Android Application 

The first step is to create a simple Android Application using Eclipse IDE. Follow the option File -> New -> Project and finally select Android New Application wizard from the wizard list. Now name your application as MySampleApp  using the wizard window as follows


Next, you create a simple application with a single activity, along with a UI layout stored in main.xml. The layout contains a text element you're going to modify to say Android   MySampleApp  . The simple layout is shown below.

Listing 1. MySampleApp  layout

The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file:.

Listing 2. strings.xml



The application has a Java source file called   MySampleApp  .java, as shown below.

The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for MySampleApp :

The code is  directly from the New Project wizard:

  • It is part of a Java package called com.msi.  MySampleApp  .
  • It has two imports:
    • One for the activity class
    • One for the bundle class
  • When this activity is initiated, the onCreate method is invoked, passing in a savedInstanceState. Don't be concerned with this bundle for our purposes; it is used when an activity is suspended and then resumed.
  • The onCreate method is an override of the activity class method of the same name. It calls the super class's onCreate method.
  • A call to setContentView() associates the UI layout defined in the file main.xml. Anything in main.xml and strings.xml gets automatically mapped to constants defined in the R.java source file. Never edit this file directly, as it is changed upon every build.

Running the Application

Let's try to run our MySampleApp application we just created. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display finally following Emulator window:






SCENARIO: 

Create layout in android with some customized buttons.try to visualize in multiple screen sizes.The image appears proper on screen size 2.7 to 5.1. However buttons appear stretched on screen size 5.4 and greater .
Usually developers use multiple same images(like img01,img02..) , named them similarly of different densities and placed them correspondingly in the folders ldpi,mdpi,hdpi,xhpi.
Bad idea... how many images you will include? think of performance,optimization on priority.

SOLUTION

I was discussing with one of my colleagues and he was considering it as great challenge .wondering what is need of defining different layout folders(layout-land, layout-large, layout-small) if care will be taken in layouts consistently. The Android OS will take care of that(regarding images display). Only thing developer is going to take care is to do is add the <support-screens> in your manifest and below is the <support-screens>:

 <supports-screens android:resizeable=["true"| "false"]
              android:smallScreens=["true" | "false"]
              android:normalScreens=["true" | "false"]
              android:largeScreens=["true" | "false"]
              android:xlargeScreens=["true" | "false"]
              android:anyDensity=["true" | "false"]
              android:compatibleWidthLimitDp="integer"
              android:largestWidthLimitDp="integer"/>

I agree there are better practices to be fallowed along with this like
    Dont hard-code any layout parameters such as height,width etc..
    Dont use "px".Use "sp" for Text Size and "dp" for layout-width, layout-height etc.
    Prefer ScrollView wherever required for layouts as it supports for a singleView.
    Make use of RelativeLayout and LinearLayout and dont use AbsoluteLayout.

Screens supported

From Android 1.6 (API Level 4), there is support for multiple screen sizes and densities, reflecting the many different screen configurations that a device may have.
To simplify the way that you design your user interfaces for multiple screens, Android divides the range of actual screen sizes and densities into:

    A set of four generalized sizes: small, normal, large, and xlarge
    A set of four generalized densities: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high)

The different resource configurations that you can specify based on the space available for your layout are summarized in below table

characteristic Qualifier Description
Size small Resources for small size screens.
normal Resources for normal size screens. (This is the baseline size.)
large Resources for large size screens.
xlarge Resources for extra large size screens.
Density ldpi Resources for low-density (ldpi) screens (~120dpi).
mdpi Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpi Resources for high-density (hdpi) screens (~240dpi).
xhdpi Resources for extra high-density (xhdpi) screens (~320dpi).
nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density.
tvdpi Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.
Orientation land Resources for screens in the landscape orientation (wide aspect ratio).
port Resources for screens in the portrait orientation (tall aspect ratio).
Aspect ratio long Resources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.
notlong Resources for use screens that have an aspect ratio that is similar to the baseline screen configuration.
Summary:
In this article, you learned about Android at BASIC LEVEL. Hope, the example will help you to explore more of the Android platform.

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... 

HOW TO BUY ,CREATE & HOST OR DEPLOY YOUR OWN WEBSITE

Introduction A website is a collection of Web pages, images, videos or other digital assets that is hosted on...